C++20学习日志(一):如何编译C++20

最近闲暇时在学《Beginning C++20 From Novice to Professional》这本书,写下笔记以免忘记。

自己做的练习题放在了Beginning_Cpp20_From_Novice_to_Professional_exercise上。

一开始做chapter1的练习的时候我就有点吃不消,为啥import <iostream>会报错啊?查了一下,似乎到2022年6月为止,gcc和clang还没支持完全的module(至少我没找到完整解决方案),看来得回到MSVC怀抱了。

StackOverflow上有一个问答回答了这个问题:Can't use iostream as module in C++20 (Visual Studio),特此摘抄:

Using the Visual Studio 2019 non preview version:

  1. Create an empty C++ project

  2. Open project properties Alt + Enter

  3. Go to Configuration Properties -> C/C++ -> Language, and set the C++ Language Standard option to Preview - Features from the Latest C++

  4. In the same section set Enable Experimental C++ Standard Library Modules to Yes (/experimental:module)

  5. Go to Configuration Properties -> C/C++ -> Advanced and set the Compile As option to Compile as C++ Module Internal Partition (/internalPartition)

  6. Add header file to your project, which contains an import declaration for every standard library header you want to import. For example:

    import <iostream>;
    
    int main()
    {
        std::cout << "Hello World!\n";
    }
  7. Recompile your project

  8. Done, now everything should work fine

经过实验完全可行,在Visual Studio 2022可使用。