Sean
Sean

Reputation: 551

Duplicate symbols while linking

I am trying to compile my program with this makefile but the linker is giving me some fuss saying that there are duplicate symbols. I tried playing with this makefile but I haven't had much luck. My program only has three files, pdp429.c, instructions.c, and global.h. Any help is appreciated thanks!

Here are the errors, (there are 46 of the "duplicate symbol" errors) "duplicate symbol _MASK_IN in: pdp429.o instructions.o ld: 46 duplicate symbols for architecture x86_64 collect2: ld returned 1 exit status make: *** [pdp429] Error 1"

CFLAGS = -O0 -pg -ggdb3 -Wall

all:    pdp429

pdp429: pdp429.o instructions.o
    gcc $(CFLAGS) pdp429.o instructions.o -o pdp429

pdp429.o: pdp429.c global.h
    gcc $(CFLAGS) pdp429.c -c

instructions.o: instructions.c global.h
    gcc $(CFLAGS) instructions.c -c

clean:
    rm -f *.o pdp429

Upvotes: 0

Views: 4969

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320401

You do not provide some critical information, but the immediate guess that you managed to define some entities with external linkage (i.e. variables or functions) in your globals.h header file. Since your globals.h is probably included into both of your *.c files, you end up with multiple definition error.

The MASK_IN is the obvious candidate, judging by the error messages. What is MASK_IN and how and where is it defined?

EDIT: So, here you go. Your MASK_IN is defined in globals.h as short MASK_IN = 0x0001;. This will certainly cause the multiple definition error. It looks like you actually tried to define a named constant. If so, the in C language one would typically use #define to define manifest constants, i,.e. do

#define MASK_IN 0x0001

but if you really want to use a named object, then for scalar type the best approach would be to do

static const short MASK_IN = 0x0001;

in the header file.

If your MASK_IN is intended to be a global variable (not a constant), then your only option is to use

extern short MASK_IN;

in the header file and

short MASK_IN = 0x0001;

in one (and only one) of the .c files.

Upvotes: 1

mah
mah

Reputation: 39807

You still have not provided the information people have asked for, but I'm going to go out on a limb and say:

  1. You've defined _MASK_IN inside global.h
  2. You've included global.h in multiple source files.

This would lead to the symbol being multiply defined. You should extern short _MASK_IN; in your header, and actually define it in a source file with short _MASK_IN = 0x0001;. Or better yet, assuming it's constant, simply #define it in a header file instead.

The #ifndef guards your comment says you use do not help because from one source file to the next, those guards are cleared. The #define is only valid within the source being compiled at any point in time.

Upvotes: 0

Related Questions