c++ - 从 .c 文件中定义的 .cpp 文件调用的函数

标签 c++ c linux

在项目A.vcproj中

文件A.h

#ifdef __cplusplus
extern "C" {
#endif
void functionA();
#ifdef __cplusplus
}
#endif

文件A.c

void functionA()
{
//function defined
}

在项目B.vcproj中:

文件B.h

void functionB() ;

文件B.cpp

#include "fileA.h"
#include "fileB.h"
void functionB() {
    functionA(); // error: undefined reference to 'functionA'
}

我在 Linux 上编译代码时遇到错误,请帮我解决这个问题。

最佳答案

您必须将这些文件链接在一起。

Source code ---compile--> Object files ---link--> Application

fileA.c ------------+
                    |---> fileA.o ---------+
                +---+                      |
                |                          |
fileA.h --------+                          +--> a.out
                |                          |
                +---+                      |
                    |---> fileB.o ---------+
fileB.cpp ----------+

编译成功后,链接器给出“对 XXX 的 undefined reference ”错误消息。

您需要确保所有文件都链接在一起。

$ ls
fileA.c  fileA.h  fileB.cpp  fileB.h
$ gcc -c fileA.c
$ g++ -c fileB.cpp
fileA.c  fileA.h  fileA.o  fileB.cpp  fileB.h  fileB.o
$ g++ fileA.o fileB.o
$ ls
a.out  fileA.c  fileA.h  fileA.o  fileB.cpp  fileB.h  fileB.o

关于c++ - 从 .c 文件中定义的 .cpp 文件调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11475200/

相关文章:

c++ - 使用 cast 扩大精度会导致多少精度?

c++ - 命名空间内模板类的前向声明

c++ - 从对象中获取值

c - gets() 的问题

c - METIS:不同操作系统的不同结果

linux - 如何正则表达式跟踪过程?

c++ - ifstream 不会在下一次迭代中打开文件

python - Numpy C-API : PyArrayObject provides wrong dimensions

c++ - 在 G++ 编译命令中包含 -std=c++0x 有什么意义?

linux - 使用 echo 从多个进程并行写入文件