According to the C standard, if a program defines or declares a reserved identifier, the behavior is undefined. One category of reserved identifiers is identifiers with external linkage defined in the C standard library.
For example of a program with undefined behavior, consider the following: file1.c defines a variable named time
with external linkage, which conflicts with the time
function from the standard library, declared in time.h.
file1.c:
int time;
int foo( void )
{
return time;
}
file2.c:
#include <time.h>
#include <stdio.h>
extern int foo( void );
int main( void )
{
foo();
printf( "current time = %ld\n", time( NULL ) );
return 0;
}
When the program is compiled and run, a seg fault occurs, because the time
symbol referenced in file2.c gets linked to the time
variable from file1.c, rather than the function in the C library.
$ gcc -c -o file1.o file1.c
$ gcc -c -o file2.o file2.c
$ gcc -o test file1.o file2.o
$ ./test
Segmentation fault (core dumped)
I'm wondering if there is any way for GCC to detect the usage of conflicting, reserved identifiers in user code, at compile or link time. Here's my motivation: I'm working on an application where users can write C extensions to the application, which get compiled and linked to the rest of the application. If the user's C code uses reserved identifiers like the example above, the resulting program can fail in hard-to-predict ways.
One solution which comes to mind is to run something like nm
on the user's object files, and compare the defined symbols against a list of reserved identifiers from the C library. However, I am hoping to find something in GCC which can detect the issue. Does anyone know if that is possible, or have any suggestions?