So i have this issue : i am declaring some extern global variables in my C program.
If I don’t use the -c option for gcc, i get undefined references errors. But with that -c option, the linking is not done, which means that i don’t have an executable generated.
So how do I solve this?
Here is my makefile (written thanks to Alex)
CC = gcc # compiler/linker frontend
INCL = -I$(INCL_DIR) # includes
DEFS = -D_DEBUG_ # defines
CFLAGS = -g $(INCL) $(DEFS) # compiler flags
LFLAGS = -lpthread -lm -g # linker flags
OBJ = approx.o producteur.o sequentialApproximation.o main.o
BIN = calculPi.exe
LINKOBJ = approx.o producteur.o sequentialApproximation.o main.o
RM = rm -fv
all: $(BIN)
clean:
${RM} *\~ \#*\# $(OBJ)
clean_all: clean
${RM} $(BIN)
cleanall: clean
${RM} $(BIN)
$(BIN): $(OBJ)
$(CC) $(LFLAGS) -o $@ $^
main.o: main.c
approx.o: approx.c approx.h
producteur.o: producteur.c producteur.h
sequentialApproximation.o : sequentialApproximation.c sequentialApproximation.h
.c.o:
$(CC) $(CFLAGS) -c $<
And here is the output of make : http://pastebin.com/NzsFetrn
I did declare extern variables in approx.h (extern and global) and i try to call them in approx.c, and there it doesn’t work.
Solution 1
You can’t pass
-cin your linking phase, as that will tell the compiler to skip linking.Your problem is
with
where
$(CXX)expands togcc -g -c -lpthread -lm ...get rid of the
-cthere.Only pass -c when compiling from source to object modules.
Solution 2
Re the second problem, you aren’t actually defining the variables anywhere. In your
.cfile you need the lines:(Assuming you really want global variables). This will fix the unresolved external error.
You can’t write to them until they’ve been allocated!
Notes
Also note that you can specify how to build object files from source in one rule:
and specify the dependencies without rules:
etc.
Other notes.
Also, as general rule of thumb,
CXXshould only contain the compiler name, no flags. Those should go inCXX_FLAGS. And why are you calling itCXXnotCC? Useg++if you want a C++ compiler, or useCC. Since you have.cfiles, I’ll assume C. So in your case, you should change:to
And you don’t need a separate
LINK_CXX.Sample Makefile
So a minimal Makefile should look like: