Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress Compiler warning Function declared never referenced

Tags:

So i have some code like this:

void foo (int, int);  void bar ( ) {     //Do Stuff     #if (IMPORTANT == 1)        foo (1, 2);    #endif  } 

When doing a compile without "IMPORTANT" I get a compiler Warning that foo is defined and never referenced. Which got me thinking (that is the problem).

So to fix this i just added the same #if (IMPORTANT == 1) around the function definition etc... to remove the warning, and then I started to wonder if there was a different way to suppress that warning on that function. I was looking at "unused" GCC attrib and didn't know if functions had the same attribute i could set? Is there even another way to suppress it that suppresses that warning for only that function and not the file?

like image 294
Jtello Avatar asked Jun 20 '12 17:06

Jtello


People also ask

How do I stop a GCC warning?

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code. This option also warns when a non-volatile automatic variable might be changed by a call to longjmp.

Can compiler warnings be ignored?

Unlike compilation errors, warnings don't interrupt the compilation process. They are not errors from the viewpoint of a programming language, but they may be software bugs. However, many compilers can be customized so that their warnings don't stop the compilation process. Warnings must not be ignored.

How do you stop warnings in Cmake?

Use -Wno-dev to suppress it. You can disable the warning like this when you are configuring your build.

Do compiler warnings matter?

A compiler warning signals a potentially serious problem in your code. The problems listed above are almost always fatal; others may or may not be, but you want compilation to fail even if it turns out to be a false alarm. Investigate each warning, find the root cause, and fix it.


2 Answers

In C++17 you can declare your function with [[maybe_unused]]:

[[maybe_unused]] void foo (int, int); 

This will suppress the warning and is the correct, idiomatic way to express a possibly unused function in C++17.

like image 110
TartanLlama Avatar answered Sep 20 '22 17:09

TartanLlama


I'm fairly sure the relevant warning option is this one:

-Wunused-function
Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.

So the warning should only be given for a static function, interesting. Makes sense. If a function is static it can only be used within the current file, so its definition must also be in this file.

And declaring it static inline avoids the warning, without resorting to ugly macros or compiler-specific pragmas or attributes.

like image 24
Jonathan Wakely Avatar answered Sep 20 '22 17:09

Jonathan Wakely