来自不同头文件c ++的未定义的函数引用

时间:2014-04-26 03:42:47

标签: c++

我只是试图使用一个函数,该函数的原型在一个单独的头文件(ML_hash.h)中声明,并且其声明是在单独的cpp文件中进行的。我试图在不同的头文件(HashNode.h)中调用此函数。以下是相关代码:

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

我得到的错误是:

    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

我不明白为什么C ++编译器不能识别ML_hash.cpp中定义的ML_hash函数。我确实在该cpp文件中包含了ML_hash.h。任何人都可以提供有关为何发生这种情况的见解吗?

编辑:

我使用如下所示的Makefile编译代码:

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

    all: hash

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

    clean:
            rm -f *.o

    %.o:    %.cpp
            $(C++) $(CFLAGS) $*.cpp

1 个答案:

答案 0 :(得分:2)

&#39; ld返回1退出状态&#39; - &GT;这是链接器错误,而不是编译器错误。

看起来你遇到了这个问题: Linking files in g++

编辑: 任

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

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

EDIT2与OP编辑: 我没有makefile专家,但它看起来像是哈希:&#39;目标只是缺少ML_hash.o和HashNode.cpp

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