解决 c++ 调用 c 函数报错: undefined reference to ‘xxx‘ 的问题
先上代码
main.cpp
#include "func.h"
int main() {
return add(1,4);
}
func.h
#ifndef UNTITLED_FUNC_H #define UNTITLED_FUNC_H int add(int a,int b); #endif //UNTITLED_FUNC_H
func.c
#include "func.h"
int add(int a,int b){
return a+ b;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.23) project(untitled) set(CMAKE_CXX_STANDARD 11) include_directories(./include) add_executable(untitled main.cpp src/func.c include/func.h)
代码结构如下图

编译
以上代码中只有main.cpp 是c++文件,其他文件都是c语言的;当进行编译后会提示以下错误:
====================[ Build | untitled | Debug ]================================ /usr/local/cmake_3.23.0/cmake-3.23.0/bin/cmake --build /tmp/tmp.HB9zcw9fre/cmake-build-debug --target untitled -- -j 22 Consolidate compiler generated dependencies of target untitled [ 33%] Building CXX object CMakeFiles/untitled.dir/main.cpp.o [ 66%] Building C object CMakeFiles/untitled.dir/src/func.c.o [100%] Linking CXX executable untitled /usr/bin/ld: CMakeFiles/untitled.dir/main.cpp.o: in function `main': /tmp/tmp.HB9zcw9fre/main.cpp:3: undefined reference to `add(int, int)' collect2: error: ld returned 1 exit status gmake[3]: *** [CMakeFiles/untitled.dir/build.make:113: untitled] Error 1 gmake[2]: *** [CMakeFiles/Makefile2:83: CMakeFiles/untitled.dir/all] Error 2 gmake[1]: *** [CMakeFiles/Makefile2:90: CMakeFiles/untitled.dir/rule] Error 2 gmake: *** [Makefile:124: untitled] Error 2
东西太多,我们只需要关注这一行,意思是找不到 add(int, int) 函数
/tmp/tmp.HB9zcw9fre/main.cpp:3: undefined reference to `add(int, int)'
这是因为.cpp 文件默认使用的是 c++编译器, 而 .c 文件默认使用的是 c 编译器,实际在编译的过程中,.cpp 文件调用 .c 文件中的函数就会出错.
至于为什么不能这么干,这篇文章说的很清楚, 有兴趣的请戳: https://blog.csdn.net/challenglistic/article/details/130223118
解决方案一
- 将所有的 .c 文件后缀改为 .cpp;所有的 .h 改为 .hpp
- 或者将所有的 .cpp 文件后缀改为 .c,所有的 .hpp 改为 .h(注意:代码中未用到 c++ 特性才能这么干)
解决方案二
在所有的.h文件头尾加上以下代码即可, 注意,只加头文件即可
#ifdef __cplusplus
extern "C" {
#endif
// 函数声明
#ifdef __cplusplus
}
#endif
加完后运行如下图,可以正常运行了

到此这篇关于解决 c++ 调用 c 函数报错: undefined reference to ‘xxx‘ 的问题的文章就介绍到这了,更多相关c++ 调用 c 函数报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
编译错误error: stray ‘\343’in program的解决方法
以下是对编译错误error: stray ‘\343’in program的解决方法进行了详细的分析介绍,如遇此问题的朋友们可以过来参考下2013-07-07


最新评论