9

I included <math.h> library in my C source code. But I get compilation errors.

Error: 
**undefined reference to 'sqrt'
**undefined reference to 'atan'

How can I link to <math.h> in CMakeLists.txt?

SEGV
  • 706
  • 1
  • 6
  • 16
  • Just out of curiosity - if the compiler is gcc and the taget system is Solaris, it might me necessary to use the compiler option `-lm` to statically link the math library. The same might hold for other target systems if gcc is used. – Codor Oct 22 '16 at 20:00
  • yes, i know it. But i have to build it on editor. For this i have to add "math.h" in cmakelists.txt – SEGV Oct 22 '16 at 20:02
  • Possible duplicate of [How do I tell CMake to link in a static library in the source directory?](http://stackoverflow.com/questions/14077611/how-do-i-tell-cmake-to-link-in-a-static-library-in-the-source-directory) – usr1234567 Oct 23 '16 at 05:07

2 Answers2

24

Cmakelists.txt file is like it:

cmake_minimum_required(VERSION 3.6)
project(project_name)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ")

set(SOURCE_FILES main.c)
add_executable(project_name ${SOURCE_FILES})

And you must add this command, for <math.h>

target_link_libraries(project_name PRIVATE m)

That's all.

SEGV
  • 706
  • 1
  • 6
  • 16
  • What if I'm getting: "CMake Error at CMakeLists.txt:57 (target_link_libraries): Cannot specify link libraries for target "my_target," which is not built by this project.". Am I missing something? – m4l490n Jun 14 '19 at 13:52
  • It is non standard library, isn't it? Probably, ´target_link_libraries()´ command search for library in standard directories and it cannot find your library. Maybe, you can add full path of library. – SEGV Jun 14 '19 at 16:09
1

Add below command in CMakeList.txt

target_link_libraries(${PROJECT_NAME} m)
Esmaeill
  • 19
  • 5
  • 1
    Hi @Esmaeill did you look at the answer that the OP gave - they found essentially the same answer as this answer provides? If you think there is some new insight that is provided, then please update the original answer with this extra insight. – Mr R Apr 06 '21 at 10:49