func(U arg);
}
lib.cpp
#include "lib.h"
T lib::func(U arg)
{
// implementation
}
And I have a test.cpp where I call this function. Now, if I implement the function in this way inside of the .cpp file then it won't compile saying there is an undefined reference in my test.cpp. But if I implement this right inside of the namespace lib in the header then it will work.
I am doing using namespace lib in lib.cpp so I thought this may be causing some problems, but when moving the function implementation before using namespace lib it's still the same. also I've tried doing
namespace lib
{
T func(U arg) { /* something */ }
}
too in lib.cpp and still same result. Am I doing something wrong or the problem is elsewhere? What could possibly cause this?
Now I've thought, maybe lib.cpp isn't being linked properly
is that function templated? if yes then you can't do that. Read this: https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl if you do put the implementation in a cpp file you'd want to include lib.cpp instead of lib.h and if it's not templated then you aren't including lib.cpp in compier commands. Share your build script. Well including lib.cpp would also solve this issue but it can be confusing for people, and may slightly increase build times.
and also share the exact errors you get, not your interpretation of what it is.
No, I'm not using template functions. Ok, it seems that I solved the initial problem which was caused by bad linking. Basically I'm trying to create a simple library and run a function from it from a separate .cpp file and the problem was that I wasn't linking the library with this .cpp file. So by adding target_link_libraries it solved the undefined reference error for the functions. Now I'll describe a different problem I just encountered though. After that I got a multiple definition of... error for variables I have defined in the namespace that's located in lib.h. The thing is that I'm including the header in multiple .cpp files and I thought the include guard would guarantee there won't be such problems. Fortunately these variables have built-in types and marking them constexpr was sufficient to solve. It seems that in c++17 this can be solved by inlining too. Though, following this logic I should get the multiple definitions of... error for the functions too. In fact I just found a stackoverflow question [https://stackoverflow.com/questions/12981725/include-guards-not-working] where someone was having this problem while defining functions in the header and solved by inlining. I suppose I'm not getting the error for those functions thanks to some flags in the compiler set by default.
Now I see, it isn't compiler flags, but the fact that I am implementing the function in .cpp and keeping the declaration in the header. so I should have inlined if I actually implemented it inside of the header.
Обсуждают сегодня