Jacob Garby
Jacob Garby

Reputation: 855

Add -l flag *after* the rest of the flags

I'm trying to use experimental/filesystem.

I first tried to use it directly in my project, through CMake, by adding this:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lstdc++fs")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lstdc++fs")

This didn't work, throwing a long and hard-to-read error:

CMakeFiles/miner.dir/Main.cpp.o: In function `main':
Main.cpp:(.text+0x33): undefined reference to `std::experimental::filesystem::v1::create_directories(std::experimental::filesystem::v1::__cxx11::path const&)'
CMakeFiles/miner.dir/Main.cpp.o: In function `std::experimental::filesystem::v1::__cxx11::path::path<char [6], std::experimental::filesystem::v1::__cxx11::path>(char const (&) [6])':
Main.cpp:(.text._ZNSt12experimental10filesystem2v17__cxx114pathC2IA6_cS3_EERKT_[_ZNSt12experimental10filesystem2v17__cxx114pathC5IA6_cS3_EERKT_]+0x73): undefined reference to `std::experimental::filesystem::v1::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
CMakeFiles/miner.dir/build.make:123: recipe for target 'miner' failed
make[2]: *** [miner] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/miner.dir/all' failed
make[1]: *** [CMakeFiles/miner.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

Anyway, I wasn't sure why this happened until I realised that for some reason -- something to do with filesystem being a static library -- I needed the -lstdc++11 to be right at the end of the commands.

I tested this with a small file, simply including <experimental/filesystem> and making some directories (the code isn't important).

I built it with these commands:

g++ -c test.cpp -lstdc++fs
g++ -o test test.o -lstdc++fs

This worked. Because of this, I'm sure I'm correct in thinking that the -lstdc++fs must go after the rest of the command.

I then used make VERBOSE=1 on my big CMake project, and noticed that it was doing the opposite of what I wanted: it was putting the -lstdc++fs at the beginning of the commands!

I'm sure CMake knows what it's doing more than I do, and this led me to believe that I'm doing something wrong. Is there any way to use experimental/filesystem without putting the flag at the end of the command? And if there's no better way, then I do hope that CMake has a way of doing this.

Upvotes: 1

Views: 348

Answers (1)

If you want to link to a library, tell CMake about it and don't mess around with flags which, as far as CMake is concerned, are a black box. Simply do this:

target_link_libraries(YourExeTarget stdc++fs)

Upvotes: 4

Related Questions