C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Freestanding std modules

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Tue, 2 Jul 2024 17:58:48 +0100
On Tue, 2 Jul 2024 at 16:50, Thiago Macieira via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Tuesday 2 July 2024 07:48:28 CEST pifminns deettnta via Std-Proposals
> wrote:
> > #include<iostream>
> >
> > int main()
> > {
> > }
>
> FYI for the sensible people on this thread:
>
> libstdc++ emits something via inline assembly with the above so that
> std::cin,
> cout and cerr are properly initialised, just with the #include. I believe
> this
> was necessary back in 2003 when the current version of libstdc++ was
> designed
>

Not quite. The inline assembly was added a year ago.

The inline asm just creates a reference to a symbol in libstdc++ so that
there is a dependency on the iostream init routines and the linker will be
sure to include them in a static link.


or no one cleaned up at that opportunity. With the binary compatibility
> requirements, it must continue doing that.
>

Well it has been cleared up. Before the use of the inline assembly there
was a global static object of type std::ios::Init, which contains a
Schwartz counter and initializes the global streams (std::cout etc.)

That meant every translation unit that included <iostream> would run a
global constructor, even though only the first of those did anything, and
all the others were redundant. Now every translation unit that includes
<iostream> depends on a symbol in the library (which has no runtime cost)
and the iostream init is done exactly once inside the library, with an init
priority to make it run early on startup.


> This violates "don't pay for what you don't need" and could be considered
> a
> flaw in the current libstdc++ design. But it's not a bug and is not
> required by
> the Standard,


The standard absolutely does require that inclusion of <iostream>
initializes std::cout etc. but it doesn't specify how that's done.



> as evidenced by the fact that neither libc++ nor MS STL have
> such shortcoming.
>
> It's also easy to work around: #include a more precise header, like
> fstream,
> strstream, ostream, etc.
>

Yes, if you don't need std::cout, std::cin, etc. then don't include
<iostream>. Complaining that including an unnecessary header brings in
unnecessary code is silly.

I assume that King Muppet's complaint is that the 'std' module includes
<iostream> so you don't get to choose whether it's "needed" or not. But
obviously a 'std' module for a freestanding implementation won't import
<iostream>, so won't run the code to initialize the global streams.

Received on 2024-07-02 17:00:07