標籤:

模塊相比於 #include 指令的優點是什麼?

為什麼 C++17 如果實現了模塊系統,編譯速度就會大大提升?


The binary representation of modules is automatically generated by
the compiler on an as-needed basis. When a module is imported (e.g., by
an #include of one of the module』s headers), the compiler will spawn a second instance of itself [3], with a fresh preprocessing context [4],
to parse just the headers in that module. The resulting Abstract Syntax
Tree (AST) is then persisted into the binary representation of the
module that is then loaded into translation unit where the module import
was encountered.

The binary representation of modules is persisted in the module cache.
Imports of a module will first query the module cache and, if a binary
representation of the required module is already available, will load
that representation directly. Thus, a module』s headers will only be
parsed once per language configuration, rather than once per translation
unit that uses the module.

Modules maintain references to each of the headers that were part of
the module build. If any of those headers changes, or if any of the
modules on which a module depends change, then the module will be
(automatically) recompiled. The process should never require any user
intervention.

Additionally, any linker flags required to use the http://std.io module will automatically be provided when the module is imported [1]
This semantic import model addresses many of the problems of the preprocessor inclusion model:

  • Compile-time scalability: The http://std.io
    module is only compiled once, and importing the module into a
    translation unit is a constant-time operation (independent of module
    system). Thus, the API of each software library is only parsed once,
    reducing the M x N compilation problem to an M + N problem.
  • Fragility: Each module is parsed as a standalone
    entity, so it has a consistent preprocessor environment. This completely
    eliminates the need for __underscored
    names and similarly defensive tricks. Moreover, the current
    preprocessor definitions when an import declaration is encountered are
    ignored, so one software library can not affect how another software
    library is compiled, eliminating include-order dependencies.
  • Tool confusion: Modules describe the API of
    software libraries, and tools can reason about and present a module as a
    representation of that API. Because modules can only be built
    standalone, tools can rely on the module definition to ensure that they
    get the complete API for the library. Moreover, modules can specify
    which languages they work with, so, e.g., one can not accidentally
    attempt to load a C++ module into a C program.

http://clang.llvm.org/docs/Modules.html


可以分別編譯,比如一個軟體由A,B ,C組成 ,當你修改A模塊,B,C不動 ,編譯的時候,B,C不用重新編譯。

對於大型項目,如果架構合理,事先把預測需要頻繁修改的地方放到一個模塊,可以極大的加快編譯速度。調試,生產都非常方便


推薦閱讀:

C++為什麼允許s1+s2="D";這種語句?
什麼時候應當依靠返回值優化(RVO)?
認真學完 C++ Primer 後,C++ 語言到了什麼水平?
為什麼C++編譯器不能發現未初始化的變數?

TAG:C | 編譯 | C17 |