OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Templated function yields errors if it is in .cpp file [duplicate]

  • Thread starter Thread starter Louise
  • Start date Start date
L

Louise

Guest
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:

    Code:
    #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:

    Code:
    #ifndef library_h
    #define library_h
    
    #include <stdio.h>
    
    void my_function(int);
    
    #endif

  • and my_function is coded into library.cpp:

    Code:
    #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:

    Code:
    #include <iostream>
    #include "library.h"
    
    int main() {
    
        int i=0;
    
        my_function<int>(i);
    
        std::cout << "Hello, World!\n";
        return 0;
    }

  • library.h:

    Code:
    #ifndef library_h
    #define library_h
    
    #include <stdio.h>
    
    template<class T> void my_function(T);
    
    #endif

  • library.cpp:

    Code:
    #include "library.h"
    
    template<class T> void my_function(T i){
    
        T j;
    
        j=i+1;
    
    }

I get a compilation error:

Code:
 % 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
Continue reading...
 
Top