C++中[[noreturn]]属性使用报错:首次声明未标记该属性
关于[[noreturn]]属性的编译错误问题
我最近了解了[[noreturn]]属性,尝试在一个无return语句的void返回类型函数上添加该属性,却出现编译错误。使用的是C++20及以上版本,版本应该不存在问题。在其他类似函数上尝试添加该属性也得到类似错误。
编译错误信息
[ 17%] Building CXX object CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o /home/turgut/Desktop/CppProjects/videoo-render/src/opengl/text_render.cpp:7:25: error: function ‘const void OpenGL::Text::set_background(int, int, float, int, int, int, int, float, std::string*)’ declared ‘[[noreturn]]’ but its first declaration was not 7 | [[noreturn]] const void Text::set_background( | make[2]: *** [CMakeFiles/Renderer.dir/build.make:132: CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:277: CMakeFiles/Renderer.dir/all] Error 2 make: *** [Makefile:136: all] Error 2
相关函数代码
[[noreturn]] void Text::set_background( int x, int y, float z, int w, int h, int gw, int gh, float ang, std::string* hex_color ){ background = new Background(x-w, y-h); background->color = (*hex_color).c_str(); background->bg_texture = new Texture( x - 10, (1000 - y) + 10, w, -h ,gw, gh ); background->bg_texture->init(ang, z, nullptr); }
问题分析与解决
错误核心原因
编译错误的直接原因是:[[noreturn]]属性必须在函数的所有声明和定义中保持一致。你仅在类外的函数定义上添加了该属性,但类内的函数声明(即该函数的第一个声明)并没有这个属性,导致编译器抛出不一致的错误。
除此之外还有两个关键问题:
[[noreturn]]属性误用:该属性仅适用于永远不会正常返回的函数——比如内部调用std::exit()、std::abort(),或者存在无限循环、总是抛出异常的逻辑。你的set_background函数会执行完所有逻辑后隐式返回(void类型函数无需显式return),完全不符合该属性的适用场景。即便解决了声明不一致的问题,后续也可能触发编译器警告或未定义行为。- 无效的
const void修饰:错误信息中出现的const void是无效语法——void返回类型不能被const修饰,这大概率是类内声明时的笔误,需要同步修正。
正确处理方式
针对你的当前代码,最合理的做法是直接移除[[noreturn]]属性,因为函数本身会正常返回,不需要该属性。
如果确实有需要标记永不返回的函数,需遵循以下规则:
- 在类的头文件中,函数声明时就添加
[[noreturn]]:class Text { public: [[noreturn]] void set_background(int x, int y, float z, int w, int h, int gw, int gh, float ang, std::string* hex_color); // 其他成员... }; - 类外的定义中保持属性一致(可省略,但建议统一):
[[noreturn]] void Text::set_background(/* 参数列表 */) { // 确保函数永远不会返回的逻辑,例如: std::exit(EXIT_FAILURE); }
内容的提问来源于stack exchange,提问作者Turgut
相关产品推荐
相关产品推荐

