I'm trying to build and run project that links files based on the picked C++ standard. The project file structure looks like this:
.
├── CMakeLists.txt
├── cpp-version-test
│ ├── CMakeLists.txt
│ ├── test-cpp17.cpp
│ ├── test-cpp17.hpp
│ ├── test-cpp20.cpp
│ └── test-cpp20.hpp
└── main.cpp
In the top CMakeLists.txt I set C++ standard like this:
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True)
Inside cpp-version-test
CMakeLists.txt file I run conditional:
if(CMAKE_CXX_STANDARD GREATER_EQUAL 20)
message("C++20 choosen, building test-cpp20")
add_library(cpp_version_test OBJECT test-cpp20.cpp)
else()
message("C++20 not choosen, building test-cpp17")
add_library(cpp_version_test OBJECT test-cpp17.cpp)
endif()
target_include_directories(cpp_version_test INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
And back inside the top CMakeLists.txt I glue it with the following snippet:
add_subdirectory(cpp-version-test)
list(APPEND EXTRA_LIBS cpp-version-test)
add_executable(Template main.cpp)
target_link_libraries(Template PUBLIC ${EXTRA_LIBS} compiler_flags)
target_include_directories(Template PUBLIC
"${PROJECT_BINARY_DIR}"
)
cmake --build
runs fine, Clang clogs up on linking:
[ 33%] Building CXX object CMakeFiles/Template.dir/main.cpp.o
[ 66%] Linking CXX executable Template
/usr/bin/ld: cannot find -lcpp-version-test: No such file or directory
clang-15: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [CMakeFiles/Template.dir/build.make:97: Template] Error 1
make[1]: *** [CMakeFiles/Makefile2:100: CMakeFiles/Template.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
Any help would be greatly appreciated. It's my back and forth with learning CMake.
You do this in your subdirectory:
add_library(cpp_version_test OBJECT ...)
Then in your top CMakeLists.txt:
add_subdirectory(cpp-version-test)
list(APPEND EXTRA_LIBS cpp-version-test)
add_executable(Template main.cpp)
target_link_libraries(Template PUBLIC ${EXTRA_LIBS} compiler_flags)
You mixed up the name of your directory and the name of your target. You target is named with underscores and your directory with dashes. target_link_libraries
works with target names and not directory names. Your "list(APPEND EXTRA_LIBS cpp-version-test)
" should instead be "list(APPEND EXTRA_LIBS cpp_version_test)
".
Some additional feedback: Instead of doing things the way you're doing, I would let the user set a cache variable named something like "CPP_VERSION_TEST_CXX_LANGUAGE_STANDARD
" to choose the number of the C++ language version to use and then target_compile_features(cpp_version_test <VISIBILITY> "cxx_std_${CPP_VERSION_TEST_CXX_LANGUAGE_STANDARD}")
. See docs:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments