SEGV
SEGV

Reputation: 908

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

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?

Upvotes: 15

Views: 21952

Answers (3)

Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40156

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) 

Upvotes: 0

SEGV
SEGV

Reputation: 908

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.

Upvotes: 30

Esmaeill
Esmaeill

Reputation: 67

Add below command in CMakeList.txt

target_link_libraries(${PROJECT_NAME} m)

Upvotes: 4

Related Questions