简体   繁体   English

如何知道c ++源文件是否具有main函数?

[英]How to know whether a c++ source file has a main function or not?

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. 有没有人有关于检查c ++源代码中main函数是否存在的想法,因为我想编写一个有点自动的makefile,这样带有main函数的c ++源代码将被链接,而没有main函数的c ++源代码将无法链接。

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: makefile文件:

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. 所以这是一个自动依赖生成makefile。 With this makefile, I need not modify the makefile every time I add a C++ source file. 使用这个makefile,每次添加C ++源文件时都不需要修改makefile。 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. 标题由“gcc -MM”命令确定,我想要链接的目标文件与除后缀之外的头文件共享相同的名称。 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". auto_depend_gen是我自己编写的程序,只删除“gcc -MM”生成的文件第一行的.o后缀。

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. 也许更普遍的问题是:虽然Java项目可以自动构建,但是多个.class文件具有主函数,但C ++不能。 So I just want to solve it. 所以我只是想解决它。

Appreciate more comments! 感谢更多评论!

You can use nm to list symbols in object file. 您可以使用nm列出目标文件中的符号。 Check if main is one of them. 检查main是否是其中之一。

This Linux command should give you a list of files with the main() function: 这个Linux命令应该给你一个main()函数的文件列表:

grep -Er 'main\s*\(' * | cut -d':' -f1

You should handle the case where this list have more than one file. 您应该处理此列表包含多个文件的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM