加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux clion cmakelisits undefined reference 未定义引用

发布时间:2020-12-13 23:45:31 所属栏目:Linux 来源:网络整理
导读:【背景以及环境】 ? 当我们第一次在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

【背景以及环境】

? 当我们第一次在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读