I have a large codebase that uses a number of unsafe functions, such as gmtime
and strtok
. Rather than trying to search through the codebase and replace these wholesale, I would like to make the compiler emit a warning or error when it sees them (to highlight the problem to maintenance developers). Is this possible with GCC?
I already know about __attribute__((deprecated))
, but AFAIK I can't use it since I don't have control of the header files where these functions are declared.
The deprecated declaration lets you specify a message that will display at compile time. The text of the message can be from a macro. Macros can only be marked as deprecated with the deprecated pragma.
Create a custom header deprecated.h
. In there, create your own wrapper functions, deprecated_strtok()
etcetera that merely call strtok
. Mark those with __attribute__((deprecated))
. Below those definitions, #define strtok deprecated_strtok
. Finally, use -include deprecated.h
Try this in a source file, with a gcc enough recent it should avoid developers using these both functions.
#pragma GCC poison gmtime
#pragma GCC poison strtok
The downside of it is that it is only valid for one compilation unit. If you use precompiled headers (which you surely do if your project is big), you could put them there. At least this solution does not involve decorating function declarations in system headers and works at compile time.
Poison is maybe a bit hard as it produces errors and not warnings. Does anyone know how to weaken it? At least it is a nice way to enforce a DO NOT USE FUNCTION xxx policy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With