鸿蒙 PC 基于 OpenHarmony 内核构建,全面支持 C++语言开发与运行,既复用 Linux 生态的 C++标准库(如 STL),又需适配鸿蒙内核的特有特性(如 musl libc、ARM aarch64 架构)。本文以“跨平台系统监控工具”为例,详解鸿蒙 PC 端 C++程序的环境配置、编译适配、代码开发、调试优化全流程,解决编译报错、标准库兼容、内核交互等核心问题。
std::string、std::vector)可直接使用;sysinfo、pthread),同时适配鸿蒙内核的/proc文件系统、硬件驱动框架(HDF);鸿蒙 PC 默认预装 Clang++/毕昇 C++编译器,终端执行以下命令验证:
# 检查Clang++版本(推荐)
clang++ --version
正常输出示例(鸿蒙 PC):
$ clang++ --version
OHOS (BiSheng Mobile STD 203.2.0.B175-20250723142036) clang version 15.0.4 (9e3d9b8a15b2)
Target: aarch64-unknown-linux-ohos
Thread model: posix
InstalledDir: /data/app/BiSheng.org/BiSheng_1.0/llvm/bin
解决鸿蒙 PC 端LINE_MAX未定义、STL 兼容、ARM 架构适配等问题,完整代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <sys/utsname.h>
#include <sys/sysinfo.h>
#include <cerrno>
#include <cstring>
#include <climits>
// 适配鸿蒙PC musl libc:手动定义LINE_MAX
#ifndef LINE_MAX
#define LINE_MAX 2048
#endif
// 鸿蒙系统路径常量(复用Linux /proc文件系统)
conststd::string PROC_CPUINFO = "/proc/cpuinfo";
conststd::string PROC_UPTIME = "/proc/uptime";
// 系统信息结构体(C++面向对象封装)
struct SystemInfo {
std::string os_name = "HarmonyOS";
std::string kernel_version;
std::string arch;
std::string hostname;
long cpu_cores = 0;
std::string cpu_model;
double total_mem_gb = 0.0;
double free_mem_gb = 0.0;
double used_mem_gb = 0.0;
double uptime_hours = 0.0;
};
// 工具类:读取/proc文件指定行
class ProcFileReader {
public:
static std::string readLine(const std::string& path, const std::string& key) {
std::ifstream file(path);
if (!file.is_open()) {
return"";
}
std::string line;
size_t key_len = key.length();
while (std::getline(file, line)) {
if (line.substr(0, key_len) == key) {
size_t colon_pos = line.find(':');
if (colon_pos != std::string::npos) {
std::string value = line.substr(colon_pos + 2); // 跳过": "
// 去除换行符和空格
value.erase(value.find_last_not_of("\n\r") + 1);
return value;
}
}
}
return"";
}
};
// 系统信息采集类
class SystemInfoCollector {
public:
static SystemInfo collect() {
SystemInfo info;
collectBasicInfo(info);
collectCPUInfo(info);
collectMemoryInfo(info);
collectUptimeInfo(info);
return info;
}
private:
// 采集基础系统信息
static void collectBasicInfo(SystemInfo& info) {
struct utsname sys_info;
if (uname(&sys_info) != -1) {
info.kernel_version = sys_info.release;
info.arch = sys_info.machine;
info.hostname = sys_info.nodename;
} else {
std::cerr << "Failed to read basic info: " << strerror(errno) << std::endl;
}
}
// 采集CPU信息(适配ARM架构)
static void collectCPUInfo(SystemInfo& info) {
// 获取CPU逻辑核心数
info.cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
if (info.cpu_cores == -1) {
std::cerr << "Failed to read CPU cores: " << strerror(errno) << std::endl;
info.cpu_cores = 0;
}
// 适配鸿蒙PC ARM架构(关键字:Processor)和x86(model name)
info.cpu_model = ProcFileReader::readLine(PROC_CPUINFO, "Processor");
if (info.cpu_model.empty()) {
info.cpu_model = ProcFileReader::readLine(PROC_CPUINFO, "model name");
}
if (info.cpu_model.empty()) {
info.cpu_model = "Unknown";
}
}
// 采集内存信息
static void collectMemoryInfo(SystemInfo& info) {
struct sysinfo mem_info;
if (sysinfo(&mem_info) != -1) {
// 转换为GB:1GB = 1024*1024*1024 Bytes
info.total_mem_gb = (double)mem_info.totalram * mem_info.mem_unit / (1024 * 1024 * 1024);
info.free_mem_gb = (double)mem_info.freeram * mem_info.mem_unit / (1024 * 1024 * 1024);
info.used_mem_gb = info.total_mem_gb - info.free_mem_gb;
} else {
std::cerr << "Failed to read memory info: " << strerror(errno) << std::endl;
}
}
// 采集系统运行时间
static void collectUptimeInfo(SystemInfo& info) {
std::ifstream uptime_file(PROC_UPTIME);
if (uptime_file.is_open()) {
double uptime_seconds;
uptime_file >> uptime_seconds;
info.uptime_hours = uptime_seconds / 3600;
} else {
std::cerr << "Failed to read uptime: " << strerror(errno) << std::endl;
}
}
};
// 打印系统信息(格式化输出)
void printSystemInfo(const SystemInfo& info) {
std::cout << "===== HarmonyOS PC C++ System Monitor =====\n";
std::cout << "===========================================\n";
std::cout << "\n[Basic Info]\n";
std::cout << "OS Name: " << info.os_name << "\n";
std::cout << "Kernel Version: " << info.kernel_version << "\n";
std::cout << "Architecture: " << info.arch << "\n";
std::cout << "Hostname: " << info.hostname << "\n";
std::cout << "\n[CPU Info]\n";
std::cout << "Logical Cores: " << info.cpu_cores << "\n";
std::cout << "CPU Model: " << info.cpu_model << "\n";
std::cout << "\n[Memory Info]\n";
printf("Total Memory: %.2f GB\n", info.total_mem_gb);
printf("Free Memory: %.2f GB\n", info.free_mem_gb);
printf("Used Memory: %.2f GB\n", info.used_mem_gb);
std::cout << "\n[System Info]\n";
printf("Uptime: %.2f hours\n", info.uptime_hours);
std::cout << "===========================================\n";
}
int main() {
try {
SystemInfo info = SystemInfoCollector::collect();
printSystemInfo(info);
} catch (conststd::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return1;
}
return0;
}
std::ifstream/std::string等 STL 组件,鸿蒙 PC 的libstdc++完全支持,无需替换;LINE_MAX手动定义:解决鸿蒙musl libc未暴露该宏的编译报错;/proc/cpuinfo中 CPU 型号关键字为Processor(而非 x86 的model name),代码做了双关键字兼容;strerror(errno));# 适配鸿蒙PC的C++编译命令(C++11标准)
clang++ -Wall -O2 -std=c++11 -D_POSIX_C_SOURCE=200809L -o harmony_sysmonitor main.cpp -lpthread -ldl -lm
参数 | 作用 |
|---|---|
clang++ | C++编译器(鸿蒙 PC 推荐,替代 g++,避免兼容性问题); |
-std=c++11 | 指定 C++11 标准(鸿蒙 PC 的libstdc++支持 C++11/C++17,按需调整); |
-D_POSIX_C_SOURCE=200809L | 开启 POSIX 标准宏,解决sysconf/LINE_MAX等接口的兼容性问题; |
-Wall | 开启所有警告,提前发现鸿蒙 PC 特有的语法/接口问题; |
-O2 | 二级优化(平衡性能与编译速度,避免-O3的兼容性风险); |
-lpthread -ldl -lm | 链接线程库、动态库、数学库(C++ STL 部分组件依赖); |
报错信息 | 原因 | 解决方法 |
|---|---|---|
use of undeclared identifier 'LINE_MAX' | 鸿蒙musl libc未暴露该宏 | 代码中添加#define LINE_MAX 2048; |
undefined reference to 'std::cout' | 未链接 C++标准库 | 编译命令确保使用clang++(而非clang),自动链接libstdc++; |
fatal error: iostream: No such file or directory | 缺少 C++头文件 | 执行ohpm install libstdc++-dev; |
error: 'nullptr' was not declared in this scope | 未指定 C++11+标准 | 编译命令添加-std=c++11或更高版本; |
chmod +x harmony_sysmonitor
./harmony_sysmonitor
==== HarmonyOS PC C++ System Monitor =====
===========================================
[Basic Info]
OS Name: HarmonyOS
Kernel Version: HongMeng Kernel 1.11.0
Architecture: aarch64
Hostname: localhost
[CPU Info]
Logical Cores: 20
CPU Model: AArch64 Processor rev 0 (aarch64)
[Memory Info]
Total Memory: 31.17 GB
Free Memory: 1.73 GB
Used Memory: 29.44 GB
[System Info]
Uptime: 0.00 hours
===========================================
若需分发 C++程序,可静态编译(将libstdc++、musl libc打包进可执行文件):
clang++ -Wall -O2 -std=c++11 -static -o harmony_sysmonitor main.cpp -lpthread -ldl -lm
对于复杂 C++项目,使用 CMake 管理编译配置,创建CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(harmony_sysmonitor)
# 指定C++标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# 鸿蒙PC编译选项
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2 -D_POSIX_C_SOURCE=200809L")
# 源文件(多文件时添加)
set(SOURCES main.cpp)
# 生成可执行文件
add_executable(harmony_sysmonitor ${SOURCES})
# 链接库
target_link_libraries(harmony_sysmonitor pthread dl m)
编译步骤:
# 创建构建目录
mkdir build && cd build
# 生成Makefile
cmake ..
# 编译
make
# 运行
./harmony_sysmonitor
鸿蒙 PC 端运行 C++程序的核心是“复用 Linux C++生态+适配鸿蒙细节”:
clang++/毕昇 C++编译器,避免g++的兼容性问题;LINE_MAX未定义、ARM 架构关键字适配、STL 标准库依赖等问题;-D_POSIX_C_SOURCE宏,确保 POSIX 接口正常使用,指定 C++11+标准以支持现代 C++特性;本文实现的 C++系统监控工具完全适配鸿蒙 PC 的内核特性,相比 C 语言版本,具备更好的可维护性和扩展性,可作为鸿蒙 PC 端 C++开发的基础模板,扩展至硬件驱动、网络编程、图形界面(Qt)等更复杂场景。