Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

c++ - Build project with "experimental/filesystem" using cmake

I need to add a "experimental/filesystem" header to my project

#include <experimental/filesystem>
int main() {
    auto path = std::experimental::filesystem::current_path();
    return 0;
}

So I used -lstdc++fs flag and linked with 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 next error:

CMake Error at CMakeLists.txt:9 (target_link_libraries): Cannot specify link libraries for target "testcpp" which is not built by
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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's just that the target_link_libraries() call has to come after the add_executable() call. Otherwise the testcpp target is not known yet. CMake parses everything sequential.

So just for completeness, here is a working version of your example I've 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...