最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C++调用C函数报错undefined reference to xxx问题解决方案
时间:2026-05-20 14:30:01 编辑:袖梨 来源:一聚教程网
本文将详细解析C++调用C函数时常见的"undefined reference"错误,并提供两种实用解决方案。通过实例代码演示问题根源及修复方法,帮助开发者快速解决混合编程中的链接问题。
先上代码
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函数的实现:
/tmp/tmp.HB9zcw9fre/main.cpp:3: undefined reference to `add(int, int)'
该问题的根源在于.cpp文件默认使用C++编译器,而.c文件使用C编译器。当C++代码尝试调用C函数时,由于名称修饰方式不同会导致链接失败。
解决方案一
- 将所有.c文件后缀改为.cpp,同时将.h改为.hpp
- 或将所有.cpp文件后缀改为.c,同时将.hpp改为.h(注意:此方法仅适用于未使用C++特性的代码)
解决方案二
在头文件中添加extern "C"声明,只需修改头文件部分:
#ifdef __cplusplus
extern "C" {
#endif
// 函数声明
#ifdef __cplusplus
}
#endif

通过以上两种方法可有效解决C++调用C函数时的链接错误,开发者可根据项目实际情况选择最适合的解决方案。掌握这些技巧能显著提升混合编程的兼容性和稳定性。
相关文章
- 幻想少女公会星界秘境通关技巧-幻想少女公会星界秘境实战攻略解析 05-20
- 侍忍者2026开服时间表_新区开放时间 05-20
- 宗师之上公测时间公布:具体上线日期何时揭晓 05-20
- 梦幻新诛仙:鬼王玩法全解析 05-20
- AI推文岛手机版教程:如何用ai高效创作文案与视频 05-20
- 光遇2023年2月14日每日任务如何完成 光遇2月14日每日任务攻略 05-20