You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 24.04下G++14.2编译C++23 HelloWorld代码报错求助

解决G++ 14.2编译C++23代码的两个错误

问题场景

在Ubuntu 24.04上用G++ 14.2编译C++23版本的HelloWorld代码时出现报错,相关信息如下:

原代码

import std;
using namespace std;

int main(){
    println("Hello World");
}

编译命令与错误信息

hakiza@VBox:~/cpp/ppp/ch00$ g++ -std=c++2b helloWorld.cpp -o hello
helloWorld.cpp:1:1: error: ‘import’ does not name a type
    1 | import std;
      | ^~~~~~
helloWorld.cpp:1:1: note: C++20 ‘import’ only available with ‘-fmodules-ts’, which is not yet enabled with ‘-std=c++20’
helloWorld.cpp: In function ‘int main()’:
helloWorld.cpp:5:5: error: ‘println’ was not declared in this scope
    5 |     println("Hello World");
      | ^~~~~~~

G++版本信息

hakiza@VBox:~/cpp/ppp/ch00$ g++ --version
g++ (Ubuntu 14.2.0-4ubuntu2~24.04) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

错误原因与解决方法

1. 关于import std;的模块错误

G++ 14.2对C++23标准库模块的支持尚未完全集成,即使指定-std=c++2b也无法直接使用import语法,必须额外启用模块特性且预编译标准库模块,步骤繁琐。

新手最简便的解决方式是放弃模块,改用传统头文件引用,将import std;替换为对应功能的头文件。

2. 关于println未定义的错误

println是C23新增的打印函数,G 14.2需要显式包含<print>头文件才能识别,同时编译时需指定C++23标准。

修改后的可编译代码

#include <print>
using namespace std;

int main(){
    println("Hello World");
}

正确编译命令

g++ -std=c++23 helloWorld.cpp -o hello

可选:尝试C++23模块的步骤(新手慎选)

如果一定要用模块特性,需先预编译标准库模块再编译代码:

  • 预编译模块:g++ -std=c++23 -fmodules-ts -xc++-system-header print
  • 编译代码:g++ -std=c++23 -fmodules-ts helloWorld.cpp -o hello

此步骤需处理依赖关系,容易出现环境问题,优先推荐头文件方案。

内容的提问来源于stack exchange,提问作者ezyman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:33:14