Search code examples
cglobal-variablesglobalization

Experimenting with global variables and functions in C


I'm trying to understand how global variables and functions work in C. My program compiles and works fine with gcc, but does not compile with g++. I have the following files:

globals.h:

int i;
void fun();

globals.c:

#include "stdlib.h"
#include "stdio.h"

void fun()
{
  printf("global function\n");
}

main.c:

#include "stdlib.h"
#include "stdio.h"
#include "globals.h"

void myfun();

int main()
{

  i=1;

  myfun();

  return 0;
}

And finally, myfun.c:

#include "stdlib.h"
#include "stdio.h"
#include "globals.h"

void myfun()
{
  fun();
}

I get the following error when compiling with g++:

/tmp/ccoZxBg9.o:(.bss+0x0): multiple definition of `i'
/tmp/ccz8cPTA.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status

Any ideas why? I would prefer to compile with g++.


Solution

  • Every file you include globals.h from will define "int i".

    Instead, put "extern int i;" into the header file and then put the actual definition of "int i = 1;" in globals.c.

    Putting header guards around globals.h would be sensible too.

    Edit: In answer to your question its because a #include works kind of like a cut and paste. It pastes the contents of the included file into the c file that you are calling include from. As you include "globals.h" from main.c and myfun.c you define int i = 1 in both files. This value, being global, gets put into the table of linkable values. If you have the same variable name twice then the linker won't be able to tell which one it needs and you get the error you are seeing. Instead by adding extern on the front in the header file you are telling each file that "int i" is defined somewhere else. Obviously, you need to define it somewhere else (and ONLY in one place) so defining it in globals.c makes perfect sense.

    Hope that helps :)