Home > Software engineering >  Is it valid to check if a function is defined in C?
Is it valid to check if a function is defined in C?

Time:10-21

void f();
int main(int argc, char** argv)
{
    if (f)
    {
        // other code
    }
}

With VS2017, the linker complaint about unsolved external symbol, while it works with GCC. According to C99 spec, is it valid? Or it's implementation detail?

CodePudding user response:

C standard requires that every symbol should be defined exactly once in a correct program, but does not require any diagnostic if the rule is not observed. So if you declare a function that is never defined in any compilation unit any use of that function is beyond C specification.

The gcc compiler is known to have plenty of extensions, some of which are also accepted by clang. If you know that you will only use gcc, you can use them, if you want to write portable programs you should not.

CodePudding user response:

GCC regards a declared function as always existent, even with -O0, and therefore optimizes the code to:

#include <stdio.h>

int main(int argc, char** argv)
{
    printf("Y\n");
}

If you add common warning options to the compiler command line, GCC will warn you about this, too.

CodePudding user response:

It's common to check if the weak function is defined(usually user defined callback) in embedded code.

No, it is never done as it cannot be done. Your code may have some pointers to functions and you can check if those pointers are not NULL (ie have been assigned with some function pointer references, but cant check if those references are correct).

  • Related