Build project with "experimental / filesystem" with cmake
I need to add the title "experimental / filesystem" to my project
#include <experimental/filesystem>
int main() {
auto path = std::experimental::filesystem::current_path();
return 0;
}
So I used the -lstdc ++ fs flag and linked against libstdc ++ fs.a
cmake_minimum_required(VERSION 3.7)
project(testcpp)
set(CMAKE_CXX_FLAGS "-std=c++14 -lstdc++fs" )
set(SOURCE_FILES main.cpp)
target_link_libraries(${PROJECT_NAME} /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a)
add_executable(testcpp ${SOURCE_FILES})
However, I have the following error:
CMake error in CMakeLists.txt: 9 (target_link_libraries): Unable to specify link libraries for target "testcpp" that is not built with this project.
But if I compile directly, it's ok:
g++-7 -std=c++14 -lstdc++fs -c main.cpp -o main.o
g++-7 -o main main.o /usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a
Where is my mistake?
source to share
I just target_link_libraries()
have to go after add_executable()
. Otherwise, the target testcpp
is not yet known. CMake parses everything sequentially.
So, for the sake of completeness, here is a working version of your example I tested:
cmake_minimum_required(VERSION 3.7)
project(testcpp)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# NOTE: The following would add library with absolute path
# Which is bad for your projects cross-platform capabilities
# Just let the linker search for it
#add_library(stdc++fs UNKNOWN IMPORTED)
#set_property(TARGET stdc++fs PROPERTY IMPORTED_LOCATION "/usr/lib/gcc/x86_64-linux-gnu/7/libstdc++fs.a")
set(SOURCE_FILES main.cpp)
add_executable(testcpp ${SOURCE_FILES})
target_link_libraries(${PROJECT_NAME} stdc++fs)
source to share
Unfortunately this is still an open issue: https://gitlab.kitware.com/cmake/cmake/issues/17834
As noted in the release, there is a search module that can be used at this time: https://github.com/vector-of-bool/CMakeCM/blob/master/modules/FindFilesystem.cmake , https://github.com/ lethal-guitar / RigelEngine / BLOB / Master / CMake / Modules /FindFilesystem.cmake
I would like to point out that the accepted answer is not very good as it hardcodes the library name. For example, using libc ++ instead of libstdc ++ is not considered. Also, with GCC> = 9, linking to the filesystem library is no longer required.
source to share