0
votes

I'm writing a c program. It contains following files:

A.h

#pragma once
extern int a;

A.c

int a = 1;

B.h

#pragma once
#include "A.h"

B.c

#include "B.h"

And the makefile looks like that

makefile:

objects = A.o B.o
main : $(objects)
    cc -Wall -o main $(objects)

When I use 'make' command, there is error 'duplicate symbol _a in A.o B.o'. I searched for similar problems, but it seems that in all such problems, the key is that they didn't use the 'extern' key word. And I use it. What is wrong with my program?

1
One doesn't write C programs with GNU Make. Make is used to determine "which pieces of of a large program need to be recompiled, and issue the commands to recompile them." Now remove all these object files (rm A.o B.o). and call make again. What do you see?Antti Haapala -- Слава Україні
So you need a clean target in your MakefileBasile Starynkevitch
It works. The problem is that I didn't remove previously generated .o file... I feel bad that I've been looking for what's wrong for an hour.Owen
Your problem happened because changing the .h does not trigger the recompilation, (because of your too simplistic Makefile). Consider using cmake or a higher level tool than make.pim
@pim, yeah I remember that I once forgot to use the 'extern' key word. But since the program works and the project(the project is not about make of course) is due 3 days later, I'll just use this makefile and may learn about cmake later.Owen

1 Answers

0
votes

You can get make to rebuild object files when you edit a header by putting in your Makefile a list of dependencies like the following...

A.o: A.c A.h
B.o: B.c A.h B.h

...which tells make that A.o depends on A.c and A.h and B.o depends on B.c A.h and B.h. It will then compare the last modified times and if any of the dependencies are newer than the object, it will rebuild it.