1 软件
clion
版本:2025.1.1
2 编译环境
1)安装xcode
和命令行工具
(base) ➜ xcode-select --install
#Xcode自带clang
#安装完成后,验证clang
(base) ➜ clang --version
Apple clang version 16.0.0 (clang-1600.0.26.6)
Target: arm64-apple-darwin24.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
2)安装cmake
(base) ➜ brew cmake
#安装完成后,验证cmake
(base) ➜ cmake version
cmake version 3.31.6
CMake suite maintained and supported by Kitware (kitware.com/cmake).
3)配置工具链
进入 Clion
> Settings
> Build, Execution, Deployment
> Toolchains
, CLion
通常会自动检测 Xcode
的 clang
工具链:
CMake
:CLion
自带 CMake
,显示Bundled
,或使用 Homebrew
安装的版本(/opt/homebrew/bin/cmake
)。
Build Tool:
自行检测Deleted: ninja
,也可选择其他
C Compiler
:自行检测Deleted: c
,也可选择其他
C++ Compiler
:自行检测Deleted: c++
,也可选择其他
Debugger
: CLion
自带LLDB
, Bundled LLDB
如下图所示:
3 C++的hello world
1)打开clion,创建project
,选择C++ Executable
, project
名字为demo
,其他默认,如下图所示:
2)创建成功后,demo目录下存在两个文件,CMakeLists.txt
和main.cpp
,如下图:
3)打开main.cpp
文件,运行该文件,执行失败,如下图所示:
异常堆栈如下:
c++ /Users/dev/gitrepo/clan/demo/main.cpp -o main
/Users/dev/gitrepo/clan/demo/main.cpp:1:10: fatal error: 'iostream' file not found
1 | #include <iostream>
| ^~~~~~~~~~
1 error generated.
这表示编译器(clang++
)找不到 C++
标准库中的 iostream
头文件。
iostream
头文件位于 macOS SDK
中,编译器需要知道它的位置。
查找 SDK 路径:
(base) ➜ xcrun --show-sdk-path
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk
#iostream就在上述文件夹的子文件夹下,/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1
打开CMakeLists.txt
,在Cmake
中配置iostream
头文件所在目录,如下代码:
cmake_minimum_required(VERSION 3.31)
project(demo)
set(CMAKE_CXX_STANDARD 20)
#新增iostream头文件所在目录
include_directories(${CMAKE_INCLUDE_PATH} /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1)
add_executable(demo main.cpp)
再次执行,运行成功,如下图:
希望上述教程对你有所帮助。
评论区