0

Maybe this thread could be similar to others but I need some help because I'm a CMAKE noob. I need to let the following command execute automatically in my IDE (Clion).

g++ main.cpp -L dependences/lib -lpq -o main

As you can imagine, I have libpq.dll and libpq.lib in a directory called "dependences" inside my project.

My CMakeList at the moment is like this:

cmake_minimum_required(VERSION 3.15)
project(AccessoDB)

set(CMAKE_CXX_STANDARD 17)

add_executable(AccessoDB main.cpp)

target_link_libraries(AccessoDB pq)

But I don't know how to get the library in that directory, and how to add the command at the beginning. Thanks in advance

LukeTheWolf
  • 179
  • 15
  • Does this answer your question? [CMake link to external library](https://stackoverflow.com/questions/8774593/cmake-link-to-external-library) The ways to link to an external library in CMake are listed in these answers, in particular, [this](https://stackoverflow.com/a/10550334/3987854) one is likely the best approach. – Kevin Jan 04 '21 at 17:23

1 Answers1

0

This answer assumes main.cpp, CMakeLists.txt and dependencies are in the same directory.

All parts of the command line parameters but -L dependencies/lib and -o main are already covered by the CMakeLists.txt file.

You could use the link_directories command to specify additional link directories, but personally I prefer using a imported library.

add_library(pq SHARED IMPORTED)
set_target_properties(pq PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/lib/libpq.dll"
    IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/lib/libpq.lib")

-o main can be replaced by changing the OUTPUT_NAME (or RUNTIME_OUTPUT_NAME) target property. Note that this won't get rid of the extension; In this case you'll end up with main.exe. (You could change that using the SUFFIX target property, if required.)

set_target_properties(AccessoDB PROPERTIES OUTPUT_NAME main)

The resulting cmake file should look like this.

cmake_minimum_required(VERSION 3.15)
project(AccessoDB)

set(CMAKE_CXX_STANDARD 17)

add_executable(AccessoDB main.cpp)
set_target_properties(AccessoDB PROPERTIES OUTPUT_NAME main)

# define the properties of pq library
add_library(pq SHARED IMPORTED)
set_target_properties(pq PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/lib/libpq.dll"
    IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/lib/libpq.lib")

#include directories could be added too
# target_include_directories(pq INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/include/pq")


target_link_libraries(AccessoDB pq)

Note that there may still be problems when running the exe, since the .dll is probably not in a directory listed in the PATH environment variable and does not recide in the working directory when running the exe.

fabian
  • 80,457
  • 12
  • 86
  • 114