解決 c++ 調(diào)用 c 函數(shù)報(bào)錯(cuò): 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)
代碼結(jié)構(gòu)如下圖

編譯
以上代碼中只有main.cpp 是c++文件,其他文件都是c語言的;當(dāng)進(jìn)行編譯后會(huì)提示以下錯(cuò)誤:
====================[ 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
東西太多,我們只需要關(guān)注這一行,意思是找不到 add(int, int) 函數(shù)
/tmp/tmp.HB9zcw9fre/main.cpp:3: undefined reference to `add(int, int)'
這是因?yàn)?code>.cpp 文件默認(rèn)使用的是 c++編譯器, 而 .c 文件默認(rèn)使用的是 c 編譯器,實(shí)際在編譯的過程中,.cpp 文件調(diào)用 .c 文件中的函數(shù)就會(huì)出錯(cuò).
至于為什么不能這么干,這篇文章說的很清楚, 有興趣的請戳: https://blog.csdn.net/challenglistic/article/details/130223118
解決方案一
- 將所有的 .c 文件后綴改為 .cpp;所有的 .h 改為 .hpp
- 或者將所有的 .cpp 文件后綴改為 .c,所有的 .hpp 改為 .h(注意:代碼中未用到 c++ 特性才能這么干)
解決方案二
在所有的.h文件頭尾加上以下代碼即可, 注意,只加頭文件即可
#ifdef __cplusplus
extern "C" {
#endif
// 函數(shù)聲明
#ifdef __cplusplus
}
#endif
加完后運(yùn)行如下圖,可以正常運(yùn)行了

到此這篇關(guān)于解決 c++ 調(diào)用 c 函數(shù)報(bào)錯(cuò): undefined reference to ‘xxx‘ 的問題的文章就介紹到這了,更多相關(guān)c++ 調(diào)用 c 函數(shù)報(bào)錯(cuò)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言中隨機(jī)數(shù)rand()函數(shù)詳解
大家好,本篇文章主要講的是C語言中隨機(jī)數(shù)rand()函數(shù)詳解,感興趣的同學(xué)感快來看一看吧,對你有幫助的話記得收藏一下2022-02-02
C++實(shí)現(xiàn)學(xué)生選課系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)學(xué)生選課系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
c++中拷貝構(gòu)造函數(shù)的參數(shù)類型必須是引用
如果拷貝構(gòu)造函數(shù)中的參數(shù)不是一個(gè)引用,即形如CClass(const CClass c_class),那么就相當(dāng)于采用了傳值的方式(pass-by-value),而傳值的方式會(huì)調(diào)用該類的拷貝構(gòu)造函數(shù),從而造成無窮遞歸地調(diào)用拷貝構(gòu)造函數(shù)。因此拷貝構(gòu)造函數(shù)的參數(shù)必須是一個(gè)引用2013-07-07
C++實(shí)現(xiàn)俄羅斯方塊(windows API)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)俄羅斯方塊,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06

