简体   繁体   中英

Why? Executable size cuts dramatically after changing build structure

I am on my personal C++ project that builds a simple compiler, called simplecc . Today, I triggered a refactor on it, which changed the way the main executable is built, or as I termed it, the build structure and the executable code size drops nearly a half.

My project has many components, such as the AST and CodeGen , which are named after their functionalities. Each component resides in its own folder (both headers and cpp's do). There is a lib/ directory that holds directories for all other components and a CMakeList.txt in lib/ generates a single executable simplecc . Now here is the difference.

The old code:

# 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...
)

The new code:

# 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)

and within each sub-directory, a static library (archive) is built from the source of that component. Finally these archives are linked into the executable.

While I think I just organized the code so that it is better tracked by cmake , it cut the code size of the executable dramatically! The old code is 14M and 3.7M after stripped. The new code is 2.4M before stripped 5.6M and 560K after stripped. How can this happen? It is generally true? It is project-specific? My project makes use of CRTP extensively.

Edit : these data is derived from a Debug build. I haven't done a Release build (will be added later).

The code size shrinks because some components are mistakenly omitted from main() and not linked in. No magic or secret. Don't try to figure out any more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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