CLion - Enabling <math.h> for C projects

Hello there ))

Have a little question about math.h library.

From what I know  (a bit googling) math.h is not enabled by default, so a compiler raises an error: "undifined referece to pow"

In order to get run I need to provide "-lm" flag (google told me so ^_^)

The question is: where exactly should I write this flag in CLion?

I've tried to play with CMake options but no result.

Any help will be highly appreciated. )))

6 comments
Comment actions Permalink

Hi Ivan.

Please do the following steps:
1) add #include <math.h>
2) add target_link_libraries(<target_name> m) in CMakeLists.txt
The second command allows you to link with libm for the math functions.

2
Comment actions Permalink

Fantastic!!! Thanks a lot!! ^_^

0
Comment actions Permalink

I am very new to this and don't understand this answer, yet have the same question. This is my cmake file:

 

cmake_minimum_required(VERSION 3.5)
project(log)

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

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

What exactly should it look like to do what you've stated above?

0
Comment actions Permalink

@Alex Alexzander, you just need to add the lib (m) toi your target (log, as defined with add_executable). It should look like this:

cmake_minimum_required(VERSION 3.6)
project(log)

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



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

target_link_libraries(log m)

 

 

 

2
Comment actions Permalink

My program still can't find the M_PI :/ 

 

//---------------------------------------------------------------CMakeList
cmake_minimum_required(VERSION 3.6)
project(Section3_Lecture21_Constants)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -Wall -pedantic")

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

target_link_libraries(Section3_Lecture21_Constants m)


//--------------------------------------------------------main.c

#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {
#define PI 3.141593
printf("%f\n",PI);
printf("%.10f\n", M_PI);
return 0;
}
 
0
Comment actions Permalink

Hi Gautea10, try to user the above macro before the "math.c" inclusion:

#define _USE_MATH_DEFINES

 

Like that:

 


#include
<stdio.h>
#define _USE_MATH_DEFINES

#include <math.h>

int main(int argc, char *argv[]) {
#define PI 3.141593
printf("%f\n",PI);
printf("%.10f\n", M_PI);
return 0;
}

Best regards,

0

Please sign in to leave a comment.