Originally Posted by
Babkockdood
I've been doing that for months, and it always works how I want it to. Maybe I just have a magic compiler.
I think "magic" is a euphemism for not behaving well. The following is my guess at what you're doing that "works", but it failed on my system (Linux/GCC):
Code:
// globals.h
#ifndef globals_h__
#define globals_h__
int x = 3; // no extern means foo.c and bar.c will both have their own x
extern void bar(void);
#endif // globals_h__
// foo.c
#include <stdio.h>
#include "globals.h"
int main(void)
{
printf("main(): x: %d\n", x);
x = 17; // which x? there are two global x's, one in foo.c and one in bar.c
printf("main(): x: %d\n", x);
bar();
printf("main(): x: %d\n", x);
return 0;
}
// bar.c
#include <stdio.h>
#include "globals.h"
void bar(void)
{
x = 42; // which x? there are two global x's, one in foo.c and one in bar.c
printf("bar(): x: %d\n", x);
}
Code:
$ gcc -Wall -c foo.c # no problem, only one x, in foo.c
$ gcc -Wall -c bar.c # no problem, only one x, in bar.c
$ gcc -Wall foo.o bar.o # now i try to combine them into one program
bar.o:(.data+0x0): multiple definition of `x'
foo.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
There are two x's, one in foo.c (from globals.h) and another in bar.c (also from globals.h). The x = 17 and x = 42 lines don't know which of the two x's to use. They're both global in scope, available to any c code using those object files.
Can you provide a simple example that works for you? What compiler/linker are you using?