13

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
  • 848
  • 1
  • 8
  • 19
  • 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
  • @usr1234567 no, it is not, there is *nothing* there that helps nor matches SEGV's answer here. This is a very obscure usage. – mckenzm Dec 02 '22 at 06:37

2 Answers2

29

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
  • 848
  • 1
  • 8
  • 19
  • 1
    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
3

Add below command in CMakeList.txt

target_link_libraries(${PROJECT_NAME} m)
Esmaeill
  • 47
  • 5
  • 3
    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