0

So this is how my defs.h is structured:

#ifndef DEF_H
#define DEF_H
#include <stdio.h>

...

int var = 20;
int test = 1;

...

#endif

Now, I have main.c and util.c, all with:

#include "defs.h"

This is my makefile:

all: clean compile

compile: clean main
    @echo SUCCESS: COMPILED FILES

main: main.o util.o
    cc main.o util.o -o progname

main.o: main.c
    cc -o main.o -c main.c

util.o: util.c
    cc -o util.o -c util.c

clean:
    -rm -rf *.a *.o *.so progname
    @echo SUCCESS: CLEANED FILES

However, when I run make, both object files compile fine, but when doing the final linking I keep getting:

util.o:(.data+0x0): multiple definition of `var'
main.o:(.data+0x0): first defined here

Am I structuring something wrong? Any help would be appreciated.

Thanks

Pat
  • 649
  • 1
  • 8
  • 24

2 Answers2

3

Yes, you are structuring something wrong.

For any particular variable, you may have several declarations, but only one definition. By placing the definition of your variables in your header, you have violated this rule. Assuming that your header is included in each of them, you now have definitions in both the main and util translation units.

A correct pattern is to place extern int var; in your header, thus providing a declaration to every translation unit that includes your header; and int var = 20; in exactly one of your source code files, thus providing one definition.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • I did this and now I am getting "util.c:(.text+0x346): undefined reference to `var`" – Pat May 03 '13 at 20:16
  • Now you are missing the `int var = 20;`. It should go at file scope into one of your `.c` files. – Robᵩ May 03 '13 at 20:36
2

Yes, you should keep your global variables in your implementation files (.c). If you have them in headers, than they get included in multiple implementation files and you get the multiple definition error.

Even better, you shouldn't have any global variables in your program.

piokuc
  • 25,594
  • 11
  • 72
  • 102