18

Work on Ubuntu 16

I used g++ main.cpp -lpq command for compiler my small project. Now I use Clion and wanna do same what I do with g++. But I can't add compiler flags in cmake file and get compile error.

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})

Also I run only cmake file and get CMAKE_CXX_FLAGS with -lpq flag.

CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done

How properly add compiler flags to cmake file?

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • 1
    Flag `-l` is for **linker**, not for *compiler*. This flag is used for link with libraries. CMake has special command [target_link_libraries](https://cmake.org/cmake/help/v3.7/command/target_link_libraries.html) for that purpose. – Tsyvarev Mar 31 '17 at 08:59
  • 1
    Thanks! Add `target_link_libraries(day_g pq)` and all works fine! Can you post you answer so I can mark as asnwer. – Metal Evolution Studio Mar 31 '17 at 09:03
  • You are not the first person who asks about given problem, but I agree that other questions are not easily searchable. Trying to make given question *canonical*. – Tsyvarev Mar 31 '17 at 09:12

2 Answers2

23

Flag -l is for linker, not for compiler. This flag is used for link with libraries. CMake has special command target_link_libraries for that purpose:

target_link_libraries(day_g pq)
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • this worked well for me too, with GSL libraries. In order to work though you have to cancel the `set(CMAKE_CXX_FLAGS "-lpq")` and the `add_definitions(-lpq)` from the previous example. – Duccio Piovani Apr 23 '18 at 09:16
  • 1
    @DuccioPiovani: The question describes the proper way for linking. This implies that other linking attempts (via *CMAKE_CXX_FLAGS* or `add_definitions`) are not needed. – Tsyvarev Apr 23 '18 at 09:29
4

-lq is not a compiler flag (CFLAGS) but a linker flag.

To pass a library in a CMake project you should use:

target_link_libraries(target_name libraries...)

Note that if you specify 'q' as library the project will link with libq.a or, if you are on windows q.dll.

... in your CMakeLists.txt the correct line to add is:

target_link_libraries(day_g pq)

Note also that when you add a CFLAG you should also "remember" the previous ones that may be added by libraries or by your platform, ie:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")

To check the exact flags cmake is passing to compiler or linker you can always run, from the build directory, the following command:

make VERBOSE=1
gabry
  • 1,370
  • 11
  • 26