malajedala malajedala - 4 years ago 70
C Question

Compiling error with errors like "multiple definition"

I am trying to compile my C program and I am getting some weird compiling errors and I have no idea where it is coming from. I already found similar posts, but their solution of specifying the output with -o is not working.

SO this is how my makefile looks like (shortened up):

CC = gcc -O3 -Wextra -Wall -pg -g -std=c99

OBJ = ./src/main.o ./src/FUNC.o ./src/getRoot.o ./src/getTree.o

out: $(OBJ)
g++ -std=c99 -g -o ./myProgramm $(OBJ)


./src/FUNC.o: src/FUNC.c
$(CC) -c src/FUNC.c -o ./src/FUNC.o

./src/main.o: src/main.c
$(CC) -c src/main.c -o ./src/main.o

./src/getRoot.o: src/getRoot.c
$(CC) -c src/getRoot.c -o ./src/getRoot.o

./src/getTree.o: src/getTree.c
$(CC) -c src/getTree.c -o ./src/getTree.o


This is a part of the errors i am getting:

./src/FUNC.o:(.rodata+0x78): multiple definition of `khStrInt'
./src/main.o:(.rodata+0x0): first defined here
./src/FUNC.o: In function `get_nbr_edge_kmer':
/home/Documents/EXAMPLE_CODE/src/FUNC.c:126: multiple definition of `DISTANCE_MAX'
./src/main.o:(.rodata+0x4): first defined here
./src/getRoot.o:(.rodata+0x0): multiple definition of `DISTANCE_MAX'
./src/main.o:(.rodata+0x4): first defined here
./src/main.o:(.rodata+0x4): first defined here
./src/getTree.o:(.rodata+0x0): multiple definition of `DISTANCE_MAX'
./src/main.o:(.rodata+0x4): first defined here
./src/getRoot.o:(.rodata+0x0): multiple definition of `khStrInt'


Does someone maybe have some idea what i am doing wrong here :/

Answer Source

Inside your header file, you should declare your variable like:

extern const int khStrInt;

Then in a .c file, you should define it like:

const int khStrInt = 33;

This means the variable definition is only generated once by the compiler when compiling the .c file and so the linker doesn't see multiple definitions. Also, having the declaration in the header file allows other files which include the header to be able to use the variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download