Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent inclusion of stdio.h (or other standard header)

Tags:

c

stdio

A codebase I work with has historically tried--purposefully--to avoid dependencies on stdio.h creeping in. It has its own print formatting and mechanisms, and those are what's supposed to be used instead of printf etc.

But someone adds a dependency every so often that has to get noticed and taken out. So I tried to make an alarm for the easiest of cases:

#if !defined(NDEBUG)
   void printf(float dont_link_with_stdio_h);
#endif

The gcc people seem to have been thinking along the lines of stopping easy errors too, because there's a helpful message if you do this...whether you've included <stdio.h> or not.

conflicting types for built-in function 'printf'

There's a way to turn this warning off (-fno-builtin). And there are all kinds of approaches that would do things like filter the symbol dump for things you don't want to be there...

But is there a trivially easy non-warning-causing (if you didn't include stdio.h) way to alert someone that they've introduced an unwanted printf usage?

like image 263
HostileFork says dont trust SE Avatar asked Dec 30 '15 03:12

HostileFork says dont trust SE


1 Answers

You can redefine printf to be some nasty value that will cause a compilation or linking error. For example:

#define printf do_not_include_stdio_h
#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}

produces the output:

undefined reference to `do_not_include_stdio_h'

You can munge the macro if you want it to be an even more obscure name or include invalid symbols if you're worried that some poor soul will have defined do_not_include_stdio_h.

You can set the macro definition in the compiler flags so you don't have to manually edit the file(s). For example:

gcc -Dprintf=do_not_include_stdio_h my_file.c
like image 118
Cornstalks Avatar answered Oct 06 '22 01:10

Cornstalks