假设我们有以下代码:
#if !defined(__cplusplus)
# error This file should be compiled as C++
#endif
#include <stdio.h>
#include <string>
//#define USE_CXX_CLASS
#ifdef USE_CXX_CLASS
class SomeClass
{
public:
SomeClass() {}
~SomeClass() {}
std::string GetSomeString()
{
// case #1
}
};
#endif // USE_CXX_CLASS
int foo()
{
// case #2
}
int
main (int argc, char *argv[])
{
(void)argc;
(void)argv;
#ifdef USE_CXX_CLASS
SomeClass someInstance;
someInstance.GetSomeString();
#endif // USE_CXX_CLASS
foo();
return 0;
}
并假设要从 GCC 版本 4.2.1 编译 C++ 编译器(而不是 C 编译器),并带有 options -Wreturn-type -Werror=return-type
。如果上面的代码在没有先取消注释上面的行的情况下按原样编译//#define USE_CXX_CLASS
,那么您将看到警告但没有错误:
.../gcc-4.2.1/bin/g++ -g -fPIC -Wreturn-type -Werror=return-type test.cpp -c -o test.o
test.cpp: In function 'int foo()':
test.cpp:26: warning: control reaches end of non-void function
但如果该//#define USE_CXX_CLASS
行未注释,则警告将被视为错误:
.../gcc-4.2.1/bin/g++ -g -fPIC -Wreturn-type -Werror=return-type test.cpp -c -o test.o
test.cpp: In member function 'std::string SomeClass::GetSomeString()':
test.cpp:18: error: no return statement in function returning non-void [-Wreturn-type]
gmake: *** [test.o] Error 1
是的,一个是非成员函数(案例 #2),另一个是 C++ 函数(案例 #1)。IMO,那应该没关系。我希望这两个条件都被视为错误,并且我不想在这个时间点添加-Werror
或-Wall
(可能稍后会这样做,但这超出了这个问题的范围)。
我的子问题是:
- 是否有一些我缺少的 GCC 开关应该可以工作?(不,我不想使用
#pragma
's。) - 这是在最新版本的 GCC 中已解决的错误吗?
作为参考,我已经提出了其他类似的问题,包括以下内容: