Reputation: 353
I'm trying to build a program and seeing multiple definition issue. Here is the simplified source codes and a makefile.
I understand this mutiple definition error. But somehow I saw this was compiled in my work environment. I cannot bring my work environment here. Is there any way to avoid multiple definition error using a special gcc options? Or is some version of GCC able to handle this issue?
[Source code 1 : main.c]
#include <stdio.h>
#include <stdlib.h>
#include "data.h"
int main(void)
{
test_cfg.a1 = 1;
printf("test_cfg.a1 = %d\n", test_cfg.a1);
func();
return 0;
}
[Source code 2 : func.c]
#include <stdio.h>
#include <stdlib.h>
#include "data.h"
int func(void)
{
test_cfg.b1 = 12;
printf("test_cfg.b1 = %d\n", test_cfg.b1);
return 0;
}
[Header file : data.h]
#ifndef _DATA_H_
#define _DATA_H_
struct {
int a1;
int b1;
int c1;
} test_cfg;
int func(void);
#endif /* end of _DATA_H_ */
[Makefile]
CC = gcc
AR = ar
ARFLAGS = rcs
CFLAGS += -Wall -std=c99
SOURCE=./main.c ./func.c
OBJECTS=$(SOURCE:.c=.o)
all: app_test
app_test:$(OBJECTS)
$(CC) -o $@ $(OBJECTS)
.c.o:
$(CC) -c $(CFLAGS) $<
.PHONY: all clean
clean:
rm -f *.o app_test
[Output]
$ make
gcc -c -Wall -std=c99 main.c
gcc -c -Wall -std=c99 func.c
gcc -o app_test ./main.o ./func.o
/usr/bin/ld: ./func.o:(.bss+0x0): multiple definition of `test_cfg'; ./main.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:13: app_test] Error 1
Upvotes: 0
Views: 24