linux clion cmakelisits undefined reference undefined references

[Background and environment]

  When we first used Clion programming under Linux, you may encounter situations cited undefined undefined reference, such as the implementation of the following code:

. 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 is  // determines a number whether a prime number is high, a simple form, the time complexity 
13 is  int the isPrime ( int n-) {
 14      iF (n-< 2 ) return  0 ;
 15      // here below calls the standard library function sqrt function given 
16      Double Upper = sqrt (( Double ) n-);
. 17      for ( int I = 2 ; I <= Upper; I ++ ) {
 18 is          IF (n-I% == 0 ) return  0 ;
 . 19      }
 20 is      return  . 1 ;
 21 is  }
 22 is  
23 is  // serial number determines the number N within is a prime number 
24  void prime_sequence () {
 25      int CNT = 0 ;
 26 is      for ( int I = 2 ; I <= N; I ++ ) {
 27          IF (the isPrime (I)) {
 28              CNT ++;
 29          }
 30      }
 31 is      the printf ( " Total prime number% d \ n- " , CNT);
 32 }

Line 16 of  <math.h>  of  sqrt  function reference being given

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

The reason is that only by CMake compiler  CMakeLists.txt  gets compiled context

 

【Solution】

In  CMakeLists.txt  add a statement file, compiled instructions need to rely on standard libraries

cmake_minimum_required (VERSION 3.14 ) 

# Note: multi1 is my project name, you should replace your project name 
Project (Multi1 C) 

the SET (CMAKE_C_STANDARD 11 ) 

# main.c main function including project start 
add_executable (multi1 main.c) 

# after the project name that you need to rely on the environment, for example, I need <math.h>, then the environment need to be added after the compilation statements - LM instruction, I would add m, 
# example, I need to support multi-threading, the compiler needs - lpthread, I would add pthread, and so on. 
target_link_libraries (multi1 m pthread)

 

  【result】

 Compile and run time, use the console to print out statements at compile time (environment):

/home/user/桌面/multi1/cmake-build-debug/multi1 -lm -lpthread

 

【Reference】

  [1] https://stackoverflow.com/.../how-to-link-to-math-h-library-using-cmake

 

Guess you like

Origin www.cnblogs.com/wangnig/p/11073224.html