5

假设我们有以下代码:

#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(可能稍后会这样做,但这超出了这个问题的范围)。

我的子问题是:

  1. 是否有一些我缺少的 GCC 开关应该可以工作?(不,我不想使用#pragma's。)
  2. 这是在最新版本的 GCC 中已解决的错误吗?

作为参考,我已经提出了其他类似的问题,包括以下内容:

4

3 回答 3

1

即使没有 USE_CXX_CLASS 标志,我也确实看到了错误。即 g++ 与类成员函数和非成员函数的错误一致。g++ (GCC) 4.4.3 20100127 (红帽 4.4.3-4)

于 2010-11-23T19:55:28.577 回答
1

它已被修复,它适用于g++ 9.3:成员函数和自由函数都被视为错误-Wall -Werror=return-type

于 2021-08-25T08:51:45.127 回答
-1

在我看来,您需要的是一个围绕 gcc 的 shell 脚本包装器。

  • 将其命名为gcc-wrapperg++-wrapper
  • 在您的 Makefile 中,将 CC 和 CXX 设置为包装器。
  • 让包装器调用 GCC 并将其输出通过管道传输到另一个程序,该程序将搜索您想要的警告字符串。
  • 让搜索程序在发现警告时退出并出现错误。
于 2010-11-19T01:16:26.413 回答