Correct way to link std::filesystem with GCC 8?

At my old employer I solved it with the following function:

function( set_required_build_settings_for_GCC8 )
    # Always link with libstdc++fs.a when using GCC 8.
    # Note: This command makes sure that this option comes pretty late on the cmdline.
    link_libraries( "$<$<AND:$<CXX_COMPILER_ID:GNU>,$<VERSION_LESS:$<CXX_COMPILER_VERSION>,9.0>>:-lstdc++fs>" )
endfunction()

I had to call that function pretty early in the top-level CMakeLists.txt file in order to make sure that it is used everywhere.
Of course, you should probably instruct your linker to only link with libraries if they are used at all. (E.g. use add_link_options( LINKER:--as-needed ).)

2 Likes