Похожие чаты

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 ответов

29 просмотров
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.

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

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

Ready for some fun AND a chance to win TKO Tokens? Join us for exciting minigames in our Telegram group! 🕒 Don’t miss out—games start on today 25 October 2024, at 8 PM! Ge...
Milkyway | Tokocrypto
255
Добрый вечер. Есть вопрос, а может и предложение. Был у меня диалог в другой группе о делфи и я задался вопросом: "А нельзя ли в делфи цвет //коментария и {комментария} сде...
Kraszx
24
How are we going bro about the Raids ??
🅿️abby_FX
13
Мдя, прикол, боевая сборка запускается (именно под отладчиком) после F9 примерно полторы минуты (97 секунд если быть точным). Начал копать - проблема детектится сразу - зависа...
Александр (Rouse_) Багель
38
Всем привет! Подскажи, пожалуйста, как передать в TComboBox сразу значение и id записи. На Delphi я делал так: ComboBox1.Items.AddObject('Какое-то значение', Pointer(id запис...
Евгений
10
Keep saying it, it’s Trump or WW3. Iran will be emboldened if Harris wins by cheating. Israel will have to take the initiative against Iran. How has BTC faired everytime the...
Adz | Ferrum Network Product & Service Consultant @ Ferrum Network
1
я так понимаю, я так подозреваю, что создание такого плагина для человека, кто умеет писать плагины для делфи потребует минут 5-10 времени. но это мое подозрение. хотелось бы ...
Kraszx
7
Товарищи, кто работа с iphelper? Или может я в самой логике ошибки фигачу, не пойму.... var ifTable : PMIB_IFTABLE; size, corSize: DWORD; Buffer ...
Warfarellen
4
Здравствуйте, вопрос по структурам данных. Были у вас случаи, когда пришлось писать деревья или двунаправленные списки?
/ /
50
Коллеги, добрый вечер. Создаю коллекцию от TFPGMap, ключ - перечисление, значение - целое. Нужно отсортировать коллекцию по значению. Как это можно сделать?
Kirill Filippenok
11
Карта сайта