I am writing a C++ code split in multiple files, and I want to include a function my_function
in a .h file.
Here is the file structure:
-
main.cpp:
#include <iostream> #include "library.h" int main() { int i=0; my_function(i); std::cout << "Hello, World!n"; return 0; }
-
in library.h I include the predeclaration of
my_function
:#ifndef library_h #define library_h #include <stdio.h> void my_function(int); #endif
-
and
my_function
is coded into library.cpp:#include "library.h" void my_function(int i){ int j; j=i+1; }
I compile with g++ library.cpp main.cpp -o main.o
and the compilation returns no errors. So far, so good.
The issue:
However, if I want my_function to take a template argument and I modify the files as follows:
-
main.cpp:
#include <iostream> #include "library.h" int main() { int i=0; my_function<int>(i); std::cout << "Hello, World!n"; return 0; }
-
library.h:
#ifndef library_h #define library_h #include <stdio.h> template<class T> void my_function(T); #endif
-
library.cpp:
#include "library.h" template<class T> void my_function(T i){ T j; j=i+1; }
I get a compilation error:
% g++ library.cpp main.cpp -o main.o
ld: Undefined symbols:
void my_function<int>(int), referenced from:
_main in main-2d776a.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Why ? How may I fix this? I do see that a similar issue has been addressed here, but I am not sure that it answers the question in my specific case.
Thank you
Louise is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.