Похожие чаты

Hi. I've got this: lib.h namespace lib { T

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?

5 ответов

12 просмотров
Hayk-Zneigras Автор вопроса

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.

Hayk Zneigras
Now I've thought, maybe lib.cpp isn't being linked...

and also share the exact errors you get, not your interpretation of what it is.

Hayk-Zneigras Автор вопроса
Manav | avoid unnecessary messaging me
is that function templated? if yes then you can't ...

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.

Hayk-Zneigras Автор вопроса
Hayk Zneigras
No, I'm not using template functions. Ok, it seems...

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.

Похожие вопросы

Обсуждают сегодня

А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
At which price point will BCH, an ASIC mined coin, be succeptible to reorg attacks because of low hashrate? $10? $1? $0.1? $0.01?
Kishniev
18
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
Hello VIC team, I had previously used the “wallet.tomochain.com” with a ledger connection. Unfortunately, the site is no longer accessible and the ledger account is not visibl...
carpe noctem
7
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Карта сайта