Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marking library functions as deprecated/unusable without modifying their source code

Tags:

c++

c

gcc

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.

like image 349
Tom Avatar asked Oct 21 '09 14:10

Tom


People also ask

What is a deprecated declaration?

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.


2 Answers

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

like image 176
MSalters Avatar answered Oct 14 '22 14:10

MSalters


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.

like image 38
jdehaan Avatar answered Oct 14 '22 14:10

jdehaan