解決 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 函數報錯內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

