Does anyone have ideas about checking the existence of the main function in a c++ source, as I want to write a somewhat automatic makefile, so that the c++ sources with main function will be linked while those without main function won’t link.
Lexical or grammar parsing may be not suitable for this simple task.
Any existing command line tools or libraries will be much helpful to this automatic task.
Thanks for any ideas!
The makefile file:
VPATH = include
CPPFLAGS += -I include
CFLAGS += -I include
C_SOURCE := $(shell find . -iname '*.c')
CPP_SOURCE := $(shell find . -iname '*.cpp')
D_OBJ := $(subst .cpp,.d, $(CPP_SOURCE))
EXE := $(subst .c,, $(C_SOURCE))
EXE += $(subst .cpp,, $(CPP_SOURCE))
.PHONY: all
all: $(EXE)
include $(D_OBJ)
$(D_OBJ): %.d: %.cpp
$(CC) -MM $(CPPFLAGS) $< > $@.temp;
auto_depend_gen $@ "$@.temp" > $@;
rm -rf $@.temp
#print_msg:
# @printf "$(EXE)\n"
# @printf "$(D_OBJ)\n"
.PHONY: clean
clean:
rm $(EXE) $(D_OBJ)
So this is an automatic dependency generation makefile. With this makefile, I need not modify the makefile every time I add a C++ source file. The headers are determined by the “gcc -MM” command and the object files I want to link share the same name with the header files except the suffixes. auto_depend_gen is a program written by myself which just removes the .o suffix of the first line of the file generated by “gcc -MM”.
Some source files have main function, while some do not, so comes this problem.
Maybe a more general question is: while a Java project can be built automatically with more than one of the .class files having a main function, but C++ cannot. So I just want to solve it.
Appreciate more comments!
You can use
nmto list symbols in object file. Check ifmainis one of them.