C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++ 调用 c 函数报错

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

作者:java叶新东

本文主要讨论了C++与C混合编程时遇到的问题及解决方案,由于默认编规则不同,.cpp文件调用.c文件函数时会出现错误,下面就来详细的介绍一下解决方法,感兴趣的可以了解一下

先上代码

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

解决方案一

解决方案二

在所有的.h文件头尾加上以下代码即可, 注意,只加头文件即可

#ifdef __cplusplus
extern "C" {
#endif

  // 函数声明

#ifdef __cplusplus
}
#endif

加完后运行如下图,可以正常运行了

到此这篇关于解决 c++ 调用 c 函数报错: undefined reference to ‘xxx‘ 的问题的文章就介绍到这了,更多相关c++ 调用 c 函数报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文