main.c :(。text + 0x30):未定义引用`reciprocal'

时间:2014-10-28 17:42:21

标签: c++ c gcc

我正在尝试高级Linux编程的第一个程序。其他一些人也觉得这个问题,但阅读这些线程并没有帮助我。我也试过那些方法,但我的问题仍然存在。请帮帮我。

这是main.c

#include <stdio.h>
#include "reciprocal.hpp"

int main(int argc, char const *argv[])
{
    int i;
    i = atoi(argv[1]);
    printf("The reciprocal of %d is %g\n", i, reciprocal(i));
    return 0;
}

列出reciprocal.cpp

#include <cassert>
#include "reciprocal.hpp"

using namespace std;


    double reciprocal(int i) {
        //I should not be Zero
        assert(i != 0);
         return 1.0/i;
    }

列出reciprocal.hpp

#ifdef _cplusplus
extern "C" {
#endif

  extern double reciprocal (int i);

#ifdef _cplusplus
}
#endif

列出Makefile:

reciprocal: main.o reciprocal.o
    g++ $(CFLAGS) -o reciprocal main.o reciprocal.o

main.o: main.c reciprocal.hpp
    gcc $(CFLAGS) -c main.c -I ../include

reciprocal.o: reciprocal.cpp reciprocal.hpp
    g++ $(CFLAGS) -c reciprocal.cpp -I ../include

clean:
    rm -f *.o reciprocal

错误是:

rajat$ make
gcc  -c main.c -I ../include
g++  -c reciprocal.cpp -I ../include
g++  -o reciprocal main.o reciprocal.o
main.o: In function `main':
main.c:(.text+0x30): undefined reference to `reciprocal'
collect2: error: ld returned 1 exit status
make: *** [reciprocal] Error 1

1 个答案:

答案 0 :(得分:1)

你的宏应该__cplusplusproper macro definition)而不是_cplusplus


如何调试:在reciprocal中找到未定义的main.o

nm main.o | grep reciprocal
                 U reciprocal

reciprocal.o

中查找
  • 使用__cplusplus

    $ nm reciprocal.o | grep reciprocal
    0000000000000000 T reciprocal
    0000000000000020 r _ZZ10reciprocalE19__PRETTY_FUNCTION__
    
  • 没有(写下_cplusplus):

    $ nm reciprocal.o | grep reciprocal
    0000000000000000 T _Z10reciprocali
    0000000000000020 r _ZZ10reciprocaliE19__PRETTY_FUNCTION__