tags:

views:

309

answers:

4

how does function name scoping work across multiple c files?

i'm porting a standard gnu toolchain project to iPhone OS, and using XCode to do it.

the code builds through make, but not through xcode. when building through xcode, the linker complains that the same symbol (function) is defined in two objects. the code has two distinct source files that #include a common file between them. while... odd (to me at least), it seems to work for the standard toolchain. any ideas if this is something that's somehow handled differently through a standard makefile?

tia

+3  A: 

In C, if I remember correctly, static function names are local to the source file in which they are defined, but all other function names exist in a global namespace. So if you have file1.c with

void fn1() {}
static void fn2() {}

and file2.c with

void fn1() {}
static void fn2() {}

and you tried to compile them with something like

cc file1.c file2.c

then you would get a name conflict between the fn1 in file1.c and the fn1 in file2.c, but not between the two fn2 functions (because they're static). (Of course, you'd get a bunch of other errors too because this program doesn't do anything, but those aren't relevant to scoping.)

David Zaslavsky
i understand why the linker is complaining, i don't understand why it builds with the gnu toolchain.file lm3_template.c defines method foo()files foo.c and bar.c at some point does an #include lm3_template.clinker complains about method foo()ideas? is it a makefile trick?
kolosy
+4  A: 

All functions not marked static have global scope (they are dumped in a single namespace). Functions marked static are limited to the translation unit they are defined in.

You have a One Definition Rule violation.

One of your headers probably has a definition for a variable. E.g: in common.h you have

int foo = 42;

change it to:

extern int foo; // a declaration

and then create a common.c file where you put a definition:

int foo = 42;
dirkgently
+1  A: 

My guess is that the common header defines an inline function that is resulting in a duplicate symbol. If that is the case, prefix those functions with a static inline, or define them as inline with an extern declaration in another .c file.

codelogic
inline was added to C99 -- not all compilers will support that. otherwise a vendor specific extension is required (on the command line).
dirkgently
True, but OP is compiling on iPhone SDK, which uses gcc that supports C99.
codelogic
+1  A: 

If it compiles without errors from the Makefile, but not from your XCode project, it is most likely because the compiler's options are being set differently in the two environments. Check the Makefile to see what options are passed to 'gcc'. In particular, it's possible that the duplicate definitions are conditionally-compiled with #ifdef, and you may need to add some preprocessor definitions to your XCode project's settings.

Mark Bessey