Search code examples
cvisual-studiogcccompiler-warningscompiler-directives

Silencing Unused Static Function Warnings for a Section of Code


In the spirit of What are the consequences of ignoring: warning: unused parameter, but I have static functions that are unused,

#include <stdlib.h> /* EXIT_SUCCESS */
#include <stdio.h>  /* fprintf */

#define ANIMAL Sloth
#include "Animal.h"

#define ANIMAL Llama
#include "Animal.h"

int main(void) {
    printf("%s\n%s\n%s\n%s\n%s\n", HelloSloth(), SleepySloth(), HelloLlama(),
        GoodbyeSloth(), GoodbyeLlama());
    return EXIT_SUCCESS;
}

static void foo(void) {
}

Animal.h

#ifndef ANIMAL
#error ANIMAL is undefined.
#endif

#ifdef CAT
#undef CAT
#endif
#ifdef CAT_
#undef CAT_
#endif
#ifdef A_
#undef A_
#endif
#ifdef QUOTE
#undef QUOTE
#endif
#ifdef QUOTE_
#undef QUOTE_
#endif
#define CAT_(x, y) x ## y
#define CAT(x, y) CAT_(x, y)
#define A_(thing) CAT(thing, ANIMAL)
#define QUOTE_(name) #name
#define QUOTE(name) QUOTE_(name)

static const char *A_(Hello)(void) { return "Hello " QUOTE(ANIMAL) "!"; }
static const char *A_(Goodbye)(void) { return "Goodbye " QUOTE(ANIMAL) "."; }
static const char *A_(Sleepy)(void) { return QUOTE(ANIMAL) " is sleeping."; }

#undef ANIMAL

I absolutely want SleepyLlama to be detected as unused and optimised out of the code by a clever compiler. I don't want to hear about it; potentially, as I expand into more ANIMALs and more actions, it becomes distracting. However, I don't want to interfere with the possible warning about foo being unused.

MSVC (14) has #pragma warning(push), but apparently doesn't check anyway; gcc (4.2) and clang have -Wunused-function. I've tried https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html but they don't seem to work for functions. Is there a way to get all warnings about foo and not about SleepyLlama across different compilers?


Solution

  • Not a way of disabling warnings but you can suppress the not used warning by actually using them.

    In your animals.h add the lines -

    static const char *A_(DummyWrapper)(void) {
        (void)A_(Hello)(); 
        (void)A_(Goodbye)(); 
        (void)A_(Sleepy)(); 
        (void)A_(DummyWrapper)(); 
    }
    

    This should make the compiler not complain about unused functions.