Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing GCC 4.x to treat -Wreturn-type as an error without enabling -Werror?

Suppose we have the following code:

#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;
}

And suppose that it were to be compiled the C++ compiler (and not the C compiler) from GCC version 4.2.1 with the options -Wreturn-type -Werror=return-type. If the above code is compiled as is without first uncommenting the //#define USE_CXX_CLASS line above, then you will see a warning but no error:

.../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

But if the //#define USE_CXX_CLASS line is uncommented, then the warning is treated as an error:

.../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

Yes, one is a non-member function (case #2), and the other is a C++ function (case #1). IMO, that should not matter. I want both conditions treated as an error, and I don't want to add -Werror or -Wall at this point in time (probably will do so later, but that is out of scope of this question).

My sub-questions are:

  1. Is there some GCC switch that I am missing that should work? (No I do not want to use #pragma's.)
  2. Is this a bug that has been addressed in a more recent version of GCC?

For reference, I have already poured through other similar questions already, including the following:

  • Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
  • C question: no warning?
  • Is a return statement mandatory for C++ functions that do not return void?
like image 641
bgoodr Avatar asked Nov 15 '22 05:11

bgoodr


2 Answers

It has been fixed, it works well with g++ 9.3: both member functions and free functions are treated as error with -Wall -Werror=return-type

like image 140
Kiruahxh Avatar answered Dec 21 '22 08:12

Kiruahxh


I do see an error even w/o the USE_CXX_CLASS flag. i.e. g++ is consistent with the error for both class member functions and non member functions. g++ (GCC) 4.4.3 20100127 (Red Hat 4.4.3-4)

like image 43
Rajivji Avatar answered Dec 21 '22 08:12

Rajivji