C Cmake setup - undefined reference to pow() (despite -lm)

Viewed 4575

I'm trying to build a project (with CLion) with the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.6)
project(alfa_1)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c11 -Wall -Wextra -lm")

set(SOURCE_FILES
        src/foo.h
        src/foo.c
        src/bar.h
        src/bar.c
        src/parser.h
        src/parser.c)

add_executable(alfa_1 ${SOURCE_FILES})

In foo.c I use pow() function from math.h, which I include in foo.h. And obviously foo.h is included in foo.c. In bar.c I have main that is doing nothing. Now, standard command line compilation like this

gcc -o bar bar.c bar.h foo.h foo.c -lm

works fine but building the project yields undefined reference to pow. As one can see I included -lm flag in CmakeLists.txt file, so I don't get why this linking part is not working here

3 Answers

add the link of library in the cmakeList

add_library(math STATIC path/to/file.cpp)

add_executable(cmake_hello main.cpp)
target_link_libraries(cmake_hello math)

and in the class cpp

#include "path/to/file.hpp"

for mode detaills see this link

In Clion this configuration solved my problem:

cmake_minimum_required(VERSION 3.13)
project(K_Nearest C)

set(CMAKE_C_STANDARD 99)

add_executable(K_Nearest main.c point.h point.c group.c group.h)
target_link_libraries(K_Nearest m)

The important step was: target_link_libraries(K_Nearest m), it should come after add_executable(...) statement.

Related