我正在尝试高级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

最佳答案

您的宏中应该有__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__

关于c++ - main.c :(。text + 0x30):对`reciprocal'的 undefined reference ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26614968/

10-10 21:26