Reputation: 41
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) $< > [email protected];
auto_depend_gen $@ "[email protected]" > $@;
rm -rf [email protected]
#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!
Upvotes: 3
Views: 1558
Reputation: 15278
You can use nm
to list symbols in object file. Check if main
is one of them.
Upvotes: 5
Reputation: 3934
This Linux command should give you a list of files with the main() function:
grep -Er 'main\s*\(' * | cut -d':' -f1
You should handle the case where this list have more than one file.
Upvotes: 1