在 Linux 下用 C++ 做跨平台(Windows / macOS / Linux)开发,核心目标通常是:
一份代码,尽量少的平台差异,统一构建、统一依赖管理
下面按「实战路线」给你讲清楚怎么搞。
跨平台 C++ 首选 CMake,不是 make、不是 autotools。
cmake_minimum_required(VERSION 3.16)
project(MyApp)
add_executable(app main.cpp)
构建方式统一:
mkdir build && cd build
cmake ..
cmake --build .
支持:
#if defined(_WIN32)
// Windows
#elif defined(__APPLE__)
// macOS
#elif defined(__linux__)
// Linux
#endif
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
避免:
src/
├── common/
├── platform/
│ ├── linux/
│ ├── windows/
│ └── macos/
示例:
// file_utils.h
#ifdef _WIN32
#include "platform/windows/file_utils_win.h"
#else
#include "platform/linux/file_utils_posix.h"
#endif
不要满屏 #ifdef
vcpkg install fmt
CMake 里:
find_package(fmt CONFIG REQUIRED)
target_link_libraries(app fmt::fmt)
✅ 官方推荐(Microsoft)
conan install .
适合:
#include <filesystem>
namespace fs = std::filesystem;
✅ 跨平台
❌ 别再用 dirent.h / windows.h
std::threadstd::atomic#include <locale>
std::locale::global(std::locale("en_US.UTF-8"));
Windows 额外:
SetConsoleOutputCP(CP_UTF8);
jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
✅ 不跑 CI = 迟早崩
| 问题 | 解决 |
|---|---|
| 路径分隔符 | 用 std::filesystem |
| 大小写敏感 | Linux 敏感 |
| 动态库后缀 | .so/.dll/.dylib |
| 线程库 | 用 std::thread |
| 编译器警告 | -Wall -Wextra |
project/
├── CMakeLists.txt
├── src/
│ ├── main.cpp
│ └── platform/
└── vcpkg.json
你可以告诉我:
我可以直接给你一个 可编译的跨平台 CMake 模板。