【背景以及環境】
當我們第一次在Linux下使用Clion進行編程時,可能會遇到 未定義引用 undefined reference 的情況,比如執行下面這段代碼:
1 #include <stdio.h> 2 #include <math.h> 3 4 #define N 10000000 5 6 void prime_sequence(); 7 8 int main() { 9 prime_sequence(); 10 } 11 12 //判斷一個數是否為素數,簡單形式,時間復雜度高 13 int isPrime(int n) { 14 if(n < 2) return 0; 15 //下面這里調用標准庫函數的sqrt函數會報錯 16 double upper = sqrt((double)n); 17 for (int i = 2; i <= upper; i++) { 18 if (n % i == 0) return 0; 19 } 20 return 1; 21 } 22 23 //串行判斷N以內的數有多少為素數 24 void prime_sequence(){ 25 int cnt = 0; 26 for (int i = 2; i <= N; i++) { 27 if (isPrime(i)) { 28 cnt++; 29 } 30 } 31 printf("共找到%d個素數\n", cnt); 32 }
第16行對 <math.h> 的 sqrt 函數引用會報錯
CMakeFiles/multi1.dir/main.c.o:在函數‘isPrime’中: /home/user/桌面/multi1/main.c:23:對‘sqrt’未定義的引用 collect2: error: ld returned 1 exit status CMakeFiles/multi1.dir/build.make:83: recipe for target 'multi1' failed make[3]: *** [multi1] Error 1 CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/multi1.dir/all' failed make[2]: *** [CMakeFiles/multi1.dir/all] Error 2 CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/multi1.dir/rule' failed make[1]: *** [CMakeFiles/multi1.dir/rule] Error 2 Makefile:118: recipe for target 'multi1' failed make: *** [multi1] Error 2
原因是在CMake的編譯器只能通過 CMakeLists.txt 獲取編譯的上下文
【解決方法】
在 CMakeLists.txt 文件中添加語句,說明編譯需要依賴的標准庫
cmake_minimum_required(VERSION 3.14) # 注意:multi1是我的項目名,你應該替換成你的項目名字 project(multi1 C) set(CMAKE_C_STANDARD 11) # main.c包括項目啟動的main函數 add_executable(multi1 main.c) # 項目名后是你需要依賴的環境,比如我需要<math.h>,那么環境需要在編譯語句后添加 -lm指令,我就添加 m, # 比如我需要多線程支持,編譯需要 -lpthread, 我就添加 pthread,等等。 target_link_libraries(multi1 m pthread)
【結果】
編譯運行時,控制台打印出編譯時使用的語句(環境):
/home/user/桌面/multi1/cmake-build-debug/multi1 -lm -lpthread
【Reference】
[1] https://stackoverflow.com/.../how-to-link-to-math-h-library-using-cmake