I was reading "A Tour of C++, Third Edition" and I found this "Hello World" example:
import std;
int main() {
std::cout << "Hello, World!\n";
}
I am completely new to C++ and I wanted to try this example.
I made a file "hello.cpp" with that content and I tried to compile it with clang like this: clang hello.cpp
This gives me the error "unknown type name 'import'" because I have to specify a newer C++ version. I can do that like this:
clang --std=c++23 hello.cpp
Unfortunately the default clang version is a bit too old and gives this error:
invalid value 'c++23' in '--std=c++23'
Luckily it is easy to install a new version of clang
with brew
:
brew install llvm@17
(The default llvm version is 18 at the moment, but that gives me this error: import of module 'std' imported non C++20 importable modules
)
After installing there is some usage information about LDFLAGS
and CPPFLAGS
:
export LDFLAGS="-L/opt/homebrew/opt/llvm@17/lib/c++ -Wl,-rpath,/opt/homebrew/opt/llvm@17/lib/c++"
export CPPFLAGS="-I/opt/homebrew/opt/llvm@17/include"
Now I can compile my source like this:
/opt/homebrew/Cellar/llvm@17/17.0.6/bin/clang++ --std=c++23 -fmodules ./hello.cpp
(Don't forget -fmodules
)
This results in "a.out" that I can finally run!
The next steps are probably using cmake and getting it working with vscode, but this is it for now.
Happy coding.
Update:
I tried getting it to work with clangd in vscode, but it seems modules is not yet supported: https://github.com/clangd/clangd/issues/1293
I had a .clangd file like this:
CompileFlags:
Add: [-std=c++23, -fmodules, -L/opt/homebrew/opt/llvm@17/lib/c++, '-Wl,-rpath,/opt/homebrew/opt/llvm@17/lib/c++', -I/opt/homebrew/opt/llvm@17/include"]
Compiler: /opt/homebrew/Cellar/llvm@17/17.0.6/bin/clang++
And this in settings.json for the clangd extension:
"clangd.path": "/opt/homebrew/Cellar/llvm@17/17.0.6/bin/clangd"