0

I am simply trying to use a function whose prototype is declared in a separate header file (ML_hash.h) and whose declaration is made in separate cpp file. I am trying to call this function in a different header file (HashNode.h). Here is the relevant code:

HashNode.h:

    #ifndef HASHNODE_H
    #define HASHNODE_H

    #include "ML_hash.h"

    template < typename T >
    class HashNode
    {
       ... // function prototype declarations
    };

    template< typename T >
      void HashNode< T >::insert(int key, T* object)
      {
          ...
          int retVal = ML_hash(1, 3);
          ...
      }

      ...
      #endif

ML_hash.h:

    #ifndef INC_ML_HASH
    #define INC_ML_HASH

    int ML_hash(int level, int key );

    #endif

The error I am getting is:

    g++ -o hash Hashtest.o:  
    Hashtest.o: In function `HashNode<int>::insert(int, int*)':
    /home/adalal1/programs/class/final_project/HashNode.h:72: undefined reference to   '       ML_hash(int, int)'
    /home/adalal1/programs/class/final_project/HashNode.h:88: undefined reference to `       ML_hash(int, int)'
    Hashtest.o: In function `HashNode<int>::explode()':
    /home/adalal1/programs/class/final_project/HashNode.h:117: undefined reference to `       ML_hash(int, int)'
    collect2: error: ld returned 1 exit status

What I don't understand is why the C++ compiler doesn't recognize the ML_hash function defined in ML_hash.cpp. I did include ML_hash.h in that cpp file. Could anyone provide insight into why this is happening?

EDIT:

I compile the code with a Makefile shown below:

    C++ = g++
    CFLAGS = -c -g

    all: hash

    hash:   Hashtest.o
            $(C++) -o hash Hashtest.o

    clean:
            rm -f *.o

    %.o:    %.cpp
            $(C++) $(CFLAGS) $*.cpp
Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59
  • @0x499602D2: Absolutely not, but good try. Here may be headers and templates, but the template does not get the non-template. – Deduplicator Apr 26 '14 at 03:49

1 Answers1

4

'ld returned 1 exit status' -> this is a linker error, not a compiler error.

Looks like you are running into this issue: Linking files in g++

EDIT: Either

g++ -o hash ML_hash.cpp HashNode.cpp HashTest.cpp

or

g++ -c ML_hash.cpp
g++ -c HashNode.cpp
g++ -c HashTest.cpp
g++ -o hash ML_hash.o HashNode.o HashTest.o

EDIT2 with OP edit: I'm no makefile expert, but it looks like the 'hash:' target is just missing ML_hash.o and HashNode.cpp

hash:   HashNode.o
        ML_hash.o
        Hashtest.o
        $(C++) -o hash Hashtest.o ML_hash.o HashNode.o
Community
  • 1
  • 1
Kevin Lam
  • 445
  • 3
  • 9