C++调用C函数报错undefined reference to xxx问题解决方案

作者:袖梨 2026-05-20

本文将详细解析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)

解决c++调用c函数报错:undefinedreferenceto‘xxx‘的问题

编译

该示例中仅有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函数时,由于名称修饰方式不同会导致链接失败。

解决方案一

  1. 将所有.c文件后缀改为.cpp,同时将.h改为.hpp
  2. 或将所有.cpp文件后缀改为.c,同时将.hpp改为.h(注意:此方法仅适用于未使用C++特性的代码)

解决方案二

在头文件中添加extern "C"声明,只需修改头文件部分:

#ifdef __cplusplus
extern "C" {
#endif

  // 函数声明

#ifdef __cplusplus
}
#endif

解决c++调用c函数报错:undefinedreferenceto‘xxx‘的问题

通过以上两种方法可有效解决C++调用C函数时的链接错误,开发者可根据项目实际情况选择最适合的解决方案。掌握这些技巧能显著提升混合编程的兼容性和稳定性。

相关文章

精彩推荐