I built a static executable with CMake.Here's my CMakeLists.txt
cmake_minimum_required(VERSION 3.25)
project(tmp2)
set(CMAKE_CXX_STANDARD 20)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
add_executable(tmp2 main.cpp)
set(GCC_CXX_FLAGS ${GCC_CXX_FLAGS} "-static-libgcc -static-libstdc++")
target_link_libraries(${PROJECT_NAME}
PUBLIC /usr/lib/x86_64-linux-gnu/libboost_chrono.a
PUBLIC /usr/lib/x86_64-linux-gnu/libboost_date_time.a
PUBLIC /usr/lib/x86_64-linux-gnu/libboost_filesystem.a
PUBLIC /usr/lib/x86_64-linux-gnu/libboost_thread.a
PUBLIC /usr/lib/x86_64-linux-gnu/libboost_atomic.a
)
target_include_directories(${PROJECT_NAME}
PUBLIC /usr/local/include
PUBLIC /usr/include/
PUBLIC /usr/include/opencv4
)
But target_link_libraries
looked kind of ugly, so I decided to use target_link_directories
so I don't have write the full path to all static libraries in target_link_libaries
. So I added the following code to my CMakeLists.txt.
target_link_directories(${PROJECT_NAME}
PUBLIC /usr/lib/x86_64-linux-gnu/
PUBLIC /usr/local/lib/
)
But after I added target_link_directories
, CMake tried to link against dynamic libraries, and I got this error:
/usr/bin/ld: attempted static link of dynamic object `/usr/lib/gcc/x86_64-linux-gnu/13/libstdc++.so'
/usr/bin/ld: attempted static link of dynamic object `/lib/x86_64-linux-gnu/libm.so.6'
/usr/bin/ld: attempted static link of dynamic object `/lib/x86_64-linux-gnu/libmvec.so.1'
/usr/bin/ld: attempted static link of dynamic object `/lib/x86_64-linux-gnu/libc.so.6'
/usr/bin/ld: attempted static link of dynamic object `/lib64/ld-linux-x86-64.so.2'
collect2: error: ld returned 1 exit status
How can I build the static executable without using the full path to all static libraries?