Friday, February 18, 2022

[SOLVED] Difference between `import` and `#include`? cpp20

Issue

I don't understand why

  1. I saw import std.core; here
  2. I can't import std;
  3. I can't import std.iostream;
  4. I can #include <iostream>

Can you explain why above is happening? Maybe i guess std.iostream is not a module. Then why 1. works?

@Someprogrammerdue provided this reference, and its says

import <iostream>;         // import declaration

When I run following in my compiler

import <iostream>;

int main()
{

    return 0;
}

I get

main.cpp:1:8: error: 'iostream' was not declared in this scope
    1 | import<iostream>;

Why is this happening?


Solution

I don't understand why

  1. I saw import std.core; here

You saw what you did because you read the page and that's what was written there.

  1. I can't import std;

This is because the C++20 standard library doesn't define modules. And because no other library can (or shouldn't) define module std because that module name is reserved for language implementation / future standardisation.

  1. I can't import std.iostream;

See 2.

  1. I can #include <iostream>

That header is part of the C++20 standard library.

Then why 1. works?

The MSVC documentation explains:

Although not specified by the C++20 standard, Microsoft enables its implementation of the C++ Standard Library to be imported as modules.

P.S. Support for modules is at the moment of writing only partially implemented by all major compilers with the exception of MSVC which appears to have full implementation since 19.28 (the modular standard libary is not a requirement for this).

P.P.S. Modular standard library is planned for C++23.



Answered By - eerorika
Answer Checked By - Dawn Plyler (WPSolving Volunteer)