How to link <math.h> library using CMake?
Asked Answered
P

3

15

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?

Pohai answered 22/10, 2016 at 19:51 Comment(3)
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.Isom
yes, i know it. But i have to build it on editor. For this i have to add "math.h" in cmakelists.txtPohai
@usr1234567 no, it is not, there is nothing there that helps nor matches SEGV's answer here. This is a very obscure usage.Pintail
P
30

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.

Pohai answered 22/10, 2016 at 21:29 Comment(4)
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?Ramillies
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.Pohai
You said that your code is written in C. I think you would get an error at "-std=c++11".Hophead
Did not work for meUstkamenogorsk
W
4

Add below command in CMakeList.txt

target_link_libraries(${PROJECT_NAME} m)
Wonderstricken answered 6/4, 2021 at 6:54 Comment(2)
Hi @Wonderstricken 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.Cacodyl
@MrR I think the selected answer would give at least one error at "set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ")". It looks like the user SEGV is mixing "gcc" (C code) and "g++" (C++ code) compilers.Hophead
U
0

You need to link math library explicitly to your executable. Like,

# Define the executable of the application !
add_executable(main ${SOURCE_FILES})

# 'm' for including math library explicitly
target_link_libraries(main m) 
Ustkamenogorsk answered 8/4 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.