K
Keith Thompson
August Karlstrom said:OK, so if libgc did include the prototype for `read' in unistd.h I would
get a compilation error with my example.
Here's the example from upthread that I presume you're referring to:
#include <stdio.h>
#include <gc/gc.h>
void read(void)
{
char *s;
puts("read()");
s = GC_malloc(32);
}
int main(void)
{
read();
return 0;
}
It's not 100% clear what "if libgc did include the prototype for
`read' in unistd.h" means. I presume you mean "if the C source
file that implements part of the gc library and calls read() has
a #include <unistd.h> directive".
In fact, the relevant source file happens to be pthread_support.c,
(which contains the definition of GC_get_nprocs(), which calls read()),
and that source file *does* have a #include <unistd.h>.
No, that doesn't imply that *your* code would get a compilation
error. Your program and pthread_support.c are compiled separately;
neither directly affects the other. If there were a #include
<unistd.h> in <gc/gc.h>, then that would affect the compilation of
your source file -- but there isn't.
The problem is this: Your source file depends on gc, which depends
on POSIX. Your source file defines and uses a function named "read".
POSIX defines another function named "read", and gc calls it.
You've linked together your own object file (generated by compiling
your source file), the gc library, and the POSIX library (probably
part of your system's libc) into an executable, which doesn't work
properly because of the conflicting "read" functions.
The C standard says very little about what happens when you do
something like this (I'm fairly sure the behavior is undefined),
and it's up to you to avoid the problem. C doesn't provide a way to
have support functions with the same name, and it doesn't require
the implementation to tell you when you've tried to use two such
functions within a program. If you're lucky, the linker might warn
you about it, but in this case you weren't lucky.