1

As specified here C makes implicit declaration of functions it does not know. So I tend to make use of it for hiding implementation details. I defined the following header file:

#ifndef TEST_H
#define TEST_H

#define PRINT(msg) \
    do{\
        _print_info_msg(msg);\
        printf(msg);\
    } while(0)

#endif //TEST_H

and the corresponding C file:

#include "test.h"

void _print_info_msg(const char *str){
    printf("INFO: printing %s\n", str);
}

When compiling this code compiler warns that implicit declaration of function ‘_print_info_msg’ [-Wimplicit-function-declaration].

The benefit of this I can see is that we do not directly expose helper function (_print_info_msg) to anyone who includes test.h yet we make use of linker so _print_info_msg implementation is provided.

I'm not sure about this approach... Does it even make sense? To me it looks kind of ugly, but this is the only "use-case" I could find for implicit declaration.

Some Name
  • 8,555
  • 5
  • 27
  • 77

1 Answers1

3

TL;DR: You are leaving yourself open to bugs, and aren't really hiding anything.

C did not have the implicit declaration rule since C99, and even before it was not a feature one would advise to use. It disables static type checking on the function arguments and leaves us open to undefined behavior on several fronts.

Don't use it! That compiler warning is there solely to not break old code bases, but it should be an error. And in fact is an error when requiring the strictest conformance mode from one's compiler.

Beyond that, you aren't really hiding anything. The macro has to appear in a header file, so every translation unit will be made aware of this symbol. You aren't hiding anything like that. Not to mention the symbol must have external linkage (or your program won't link either).

So just add a function declaration after or before the macro to make certain your code is correct even when compiled by a compiler from this millennium.

Oh, and identifiers with a leading underscore at file scope are reserved to the implementation (your tool-chain). Meaning you can't have a file scope identifier with a leading underscore, for risk of nasal demons. Better rename _print_info_msg.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 2
    (Identifiers with a leading underscore followed by a capital letter or another underscore are reserved for any use. Other identifiers that merely begin with an underscore are only reserved in the ordinary and tag name spaces, in file scope. One could use them as labels [which do not have file scope], member names [which can], or preprocessor identifiers [which do not]. Essentially, the C standard is reserving a portion of the name space for hidden helper functions and objects to be linked in, and member names do not interfere those.) – Eric Postpischil Jan 20 '19 at 13:18