c++ - 链接错误 c 和 c++( undefined reference )

标签 c++ c linker makefile

abc.c文件

#include "abc.h"
int abc()
{
    return 10;
}

abc.h文件

int abc();

我的main.cpp文件

#include "abc.h"
int main()
{
    abc();
    return  0;
}

生成文件

CC=gcc -O2 
CP=g++

mymain: mymain.o abc.o
    $(CP) -o mymain mymain.o abc.o

mymain.o: mymain.cpp abc.h
    $(CP) -c mymain.cpp abc.h

abc.o: abc.c abc.h
    $(CC) -c abc.c abc.h

clean:  
    $(RM) *.o mymain

输出

g++ -c mymain.cpp abc.h
gcc -O2  -c abc.c abc.h
g++ -o mymain mymain.o abc.o
mymain.o: In function `main':
mymain.cpp:(.text+0x5): undefined reference to `abc()'
collect2: error: ld returned 1 exit status
make: *** [mymain] Error 1

为什么 abc() 是 undefined reference ??

更新

新的abc.h

extern "C" {
    int abc();
}

错误

g++ -c mymain.cpp abc.h
gcc -O2  -c abc.c abc.h
In file included from abc.c:1:0:
abc.h:1:8: error: expected identifier or ‘(’ before string constant
 extern "C" {
        ^
abc.h:1:8: error: expected identifier or ‘(’ before string constant
 extern "C" {
        ^
make: *** [abc.o] Error 1

最佳答案

问题是您试图将 C 函数链接到 C++ 对象,而不告诉编译器这是您正在做的事情。

如果您的头文件 (abc.h) 如下所示:

extern "C" {
    int abc();
}

它会起作用(当包含在 C++ 源代码中时……但当包含在 C 源代码中时会中断)。

您可以将 extern "C"{ 及其结尾的 } 包含在宏中,如 Combining C++ and C - how does #ifdef __cplusplus work? 所示。为了同时适用于 C 和 C++ 包含。

请注意,您的 makefile 中的 $(CP) -c mymain.cpp abc.h 没有意义——您不想在编译器命令行上指定 header 。这适用于该模式的两个实例。

关于c++ - 链接错误 c 和 c++( undefined reference ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293854/

相关文章:

c++ - 如何在 Qt 中将秒数( double )转换为 QDateTime?

c - 在 c 中使用 '"#include"和此链接错误?

c - 使用 GSL 的双摆解决方案

c++ - 消除未使用的虚函数

c - 在编译时重写或中断 C 单元测试的函数链接

c++ - 非模板类与模板类的多重定义

c++ - CDC::Ellipse 无法正确绘制圆圈

c++ - 我的文件依赖性有什么问题?

c++ - 如果变体之一没有特定字段,则无法访问该变体

c - 指向字符转换的不兼容指针