I'm trying to compile the following code using LLVM / clang 15.0.5 installed via MacPorts on macOS 10.13 or 10.14:
#include <filesystem>
#include <stdio.h>
int main() {
std::filesystem::path file("/file.txt");
printf("exists: %d\n", std::filesystem::exists(file));
return 0;
}
When compiling on macOS 10.13, I get the following error:
$ /opt/local/bin/clang++-mp-15 -std=c++17 test.cpp -o test
Undefined symbols for architecture x86_64:
"std::__1::__fs::filesystem::__status(std::__1::__fs::filesystem::path const&, std::__1::error_code*)", referenced from:
__ZNSt3__14__fs10filesystem6existsB6v15005ERKNS1_4pathE in test-5b7d68.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
When compiling on macOS 10.14, I don't get that linker error, but the resulting binary fails when I try to run it:
$ ./test
dyld: lazy symbol binding failed: Symbol not found: __ZNSt3__14__fs10filesystem8__statusERKNS1_4pathEPNS_10error_codeE
Referenced from: /path/to/./test
Expected in: /usr/lib/libc++.1.dylib
dyld: Symbol not found: __ZNSt3__14__fs10filesystem8__statusERKNS1_4pathEPNS_10error_codeE
Referenced from: /path/to/./test
Expected in: /usr/lib/libc++.1.dylib
Abort trap: 6
It seems in both cases it's failing to use the libraries provided by the MacPorts LLVM installation.
In another question, someone suggested using --sysroot
might fix it, but that leads to a new error:
$ /opt/local/bin/clang++-mp-15 --sysroot /opt/local/libexec/llvm-15 -std=c++17 test.cpp -o test
ld: library not found for -lc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Using /opt/local
as sysroot fails with the same error.
How do I get this to compile and run?
I'm aware that filesystem::path
was added to macOS starting in 10.15, but the whole reason I'm using a custom installation of LLVM through MacPorts is so that I can use newer C++17 features without needing to be on a later version of macOS.
edit:
This question is not a duplicate of this one. That question is referring to a much earlier version of clang, version 8, where the C++ filesystem library had just recently had support added. This question is referring to clang 15.0.5 (seven major versions later), the latest version as of this writing, which no longer requires explicitly linking to libc++fs
. Doing so no longer works and produces an error that the library is not found.
The problem here is that, after compiling, clang / LLVM is not properly finding its own libraries or linking a binary correctly, so that the symbols in reference to std::filesystem
are not found. The command I'm using is supposed to work, but for some reason isn't.