TroubleTruffle
TroubleTruffle

Reputation: 59

How do you link precompiled libraries in CMake?

# file(COPY ${CMAKE_SOURCE_DIR}/libs/glew32.lib DESTINATION ${PROJECT_BINARY_DIR}/libs)
# file(COPY ${CMAKE_SOURCE_DIR}/libs/libglfw3dll.a DESTINATION ${PROJECT_BINARY_DIR}/libs)

add_executable(${PROJECT_NAME} main.cpp)
# libs/glew32.lib
# libs/libglfw3dll.a
# "main.cpp"
# )

target_link_libraries(${PROJECT_NAME}
libs/glew32.lib
libs/libglfw3dll.a
)

I've tried doing every option here but they end up causing linking errors. I tried both compiling from src and using every available format glfw and glew provided.

Upvotes: 5

Views: 2357

Answers (2)

Anton
Anton

Reputation: 501

I usually create a CMake target first to import the prebuilt/precompiled library, then use target_link_libraries like y ou normally link to a CMake library target. The benefit is you can control the dependency being a PRIVATE dependency or a PUBLIC one.

project(YourCoolProject)

# Import a prebuilt library to a CMake target
add_library(Foo SHARED IMPORTED)
set_target_properties(Foo PROPERTIES
  IMPORTED_LOCATION_DEBUG   "/absolute-path/to/prebuilt-debug-library"
  IMPORTED_LOCATION_RELEASE "/absolute-path/to/prebuilt-release-library"
  IMPORTED_LOCATION_RELWITHDEBINFO "/absolute-path/to/prebuilt-relwithdebinfo-library"
  INTERFACE_INCLUDE_DIRECTORIES "/absolute-path/to/include-dir"
)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE Foo)

Notes:

  1. The choice of IMPORTED_LOCATION_<CONFIG> depends on the build type you provide to CMake (cmake -DCMAKE_BUILD_TYPE=<CONFIG> ...).
  2. In order to replace the absolute path, you can use find_library to utilize CMake to find your library and store it in a variable and use find_path to find the include directory.

Upvotes: 6

mdf
mdf

Reputation: 133

You probably need to use target_link_directories() as well to tell the compiler where to find the libraries:

target_link_directories(${PROJECT_NAME} ${PROJECT_BINARY_DIR}/libs/)

Upvotes: 0

Related Questions