Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

cmake

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

like image 857
micsza Avatar asked May 19 '17 14:05

micsza


Video Answer


1 Answers

CMAKE_CXX_FLAGS are flags for the C++ compiler. -l is a linker flag. To link to a library, use this:

target_link_libraries(alfa_1 m)

You might also want to replace -std=c11 with use of CMAKE_C_STANDARD and related variables (CMAKE_C_STANDARD_REQUIRED, CMAKE_C_EXTENSIONS), and possibly replace use of CMAKE_CXX_FLAGS with a call to target_compile_options().

like image 74
Angew is no longer proud of SO Avatar answered Oct 13 '22 01:10

Angew is no longer proud of SO