0

I started to create a very simple namespace that contains a hpp header file that contains the declaration of my function as bellow

modularity.hpp

#ifndef MODULARITY_HPP
#define MODULARITY_HPP
 
#include <stdlib.h>

namespace comm {
      template <class T>                                          
      int* modularity_louvain_dir(T** W, float gamma, int seed);                                                                  
}                                                               
                                                                
#endif 

I have a definition of the function that I was using just to test initially:

modularity.cpp

#include "modularity.hpp"
 
namespace comm {

  template <class T>
  int* modularity_louvain_dir(T** W, float gamma, int seed)
  {
       int *out = (int*) calloc (10,sizeof(int));
       return out;
  }
}

Usually, when I import to the main code I do so by including the header file (#include "modularity.hpp") however by doing so when I compile the main file I get the following error:

/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x253): undefined reference to `int* comm::modularity_louvain_dir<int>(int**, float, int)'
collect2: error: ld returned 1 exit status

If instead, I include modularity.cpp instead the code compiles and runs correctly. I'm having difficulty understanding why this happens, usually I don't have this problem. I'm compiling the code like this:

g++ -c modularity.cpp
g++ -c main.cpp
g++ modularity.o main.o -o main

And also, bellow is main.cpp:

#include <iostream>
#include "array.hpp"
#include "modularity.hpp"
     
int main()
{
   
  int n   = 10;
  int **W = ones(n,n);

  int* out = comm::modularity_louvain_dir(W,1.0,0);

  std::cout << "\n";
     
  for(auto i = 0; i<n; i++)
  {  
     if(i==n-1) 
        std::cout << out[i] << std::endl;
     else
        std::cout << out[i] << ", ";
  }
 
   }

Thanks!

  • Please *don't* include line-numbers in code snippets (especially if they're wrong like in your snippets)'. If you need to point out a specific line in your code, then add a comment on that line and write out it in the question body. – Some programmer dude Sep 19 '21 at 12:38
  • Where is the `tests.cpp` file? Your link error mentions it but you did not. How do you compile it? – r3mus n0x Sep 19 '21 at 12:40
  • Aside from the problem you ask about, generally if you ever need to do a C-style cast (like `(int*)`) then you should take that as a sign you're doing something wrong. In C++ don't use `malloc` or `calloc`, use `new` and `new[]`. Or better yet use smart pointers. And best, use `std::vector`. – Some programmer dude Sep 19 '21 at 12:41
  • 1
    Definition of a template function must be in a header file. Because compiller need to know which specification of the template function generate. – Sergey Aleksandrovich Sep 19 '21 at 12:41

0 Answers0