我在我的个人 C++ 项目中构建了一个简单的编译器,称为simplecc。今天,我对其进行了重构,这改变了主可执行文件的构建方式,或者如我所说,构建结构和可执行代码大小下降了近一半。
我的项目有很多组件,例如AST
和CodeGen
,它们以它们的功能命名。每个组件都驻留在自己的文件夹中(标题和 cpp 都有)。有一个lib/
目录包含所有其他组件的目录,并且一个CMakeList.txt
inlib/
生成单个可执行文件simplecc
。现在这里有区别。
旧代码:
# All source code is listed and directly built into the executable.
add_executable(simplecc
Lex/Tokenize.cpp
Lex/TokenInfo.cpp
Parse/Grammar.cpp
Parse/ASTBuilder.cpp
Parse/Parser.cpp
Parse/Node.cpp
Parse/Parse.cpp
Parse/ParseTreePrinter.cpp
# More to come...
)
新代码:
# lib/CMakeLists.txt
add_subdirectory(Lex)
add_subdirectory(Parse)
# More to come...
# Add main executable.
add_executable(simplecc Driver/main.cpp)
# Link to all components.
target_link_libraries(simplecc Driver)
# More to come.
# lib/Parse/CMakeLists.txt
add_library(Parse STATIC
ASTBuilder.cpp
Grammar.cpp
Node.cpp
Parse.cpp
Parser.cpp
ParseTreePrinter.cpp)
target_link_libraries(Parse Lex AST)
在每个子目录中,从该组件的源代码构建一个静态库(存档)。最后,这些档案被链接到可执行文件中。
虽然我认为我只是组织了代码以便更好地跟踪它cmake
,但它大大减少了可执行文件的代码大小!剥离后的旧代码是14M和3.7M。新代码剥离前为2.4M,剥离后为5.6M,剥离后为560K。这怎么可能发生?一般是真的吗?它是特定于项目的吗?我的项目广泛使用CRTP。
编辑:这些数据来自调试版本。我还没有完成发布版本(稍后会添加)。