Building C and C++ binaries statically and dynamically in the same environment

I am currently trying to create an environment that supports a certain build process.
It must support

  • building statically linked binaries from C and C++ sources
  • building dynamically linked binaries from C and C++ sources

My minimal breaking example looks like this:

#include <stdio.h>
int
main ()
{
FILE *f = fopen ("conftest.out", "w");
 return ferror (f) || fclose (f) != 0;
  ;
  return 0;
}

and

#include <cstdlib>
#include <stdio.h>
int
main ()
{
FILE *f = fopen ("conftest.out", "w");
 return ferror (f) || fclose (f) != 0;
  ;
  return 0;
}

If I have only the gcc package in my environment I can build dynamic C and C++ binaries, but static linking does not work as the linker does not find a static libc.
By including glibc.static I can build static C binaries, but the dynamically linked variant crashes with a segmentation fault in this line:

Dump of assembler code for function __libc_start_main_impl:
   0x0000000000405720 <+0>:	endbr64
   0x0000000000405724 <+4>:	push   %r15
   0x0000000000405726 <+6>:	lea    0x1(%rsi),%eax
   0x0000000000405729 <+9>:	push   %r14
   0x000000000040572b <+11>:	cltq
   0x000000000040572d <+13>:	push   %r13
   0x000000000040572f <+15>:	push   %r12
   0x0000000000405731 <+17>:	mov    %rdx,%r12
   0x0000000000405734 <+20>:	push   %rbp
   0x0000000000405735 <+21>:	mov    %esi,%ebp
   0x0000000000405737 <+23>:	push   %rbx
   0x0000000000405738 <+24>:	sub    $0xd8,%rsp
   0x000000000040573f <+31>:	mov    %rdi,0x40(%rsp)
   0x0000000000405744 <+36>:	lea    (%rdx,%rax,8),%rdi
   0x0000000000405748 <+40>:	mov    0x110(%rsp),%rax
   0x0000000000405750 <+48>:	mov    %r9,0x48(%rsp)
   0x0000000000405755 <+53>:	mov    %rdi,0x9c5c4(%rip)        # 0x4a1d20 <environ>
=> 0x000000000040575c <+60>:	mov    %rax,0x94ffd(%rip)        # 0x49a760 <__libc_stack_end>

When I additionally include the package glibc I can build static and dynamic C sources, but C++ does not work anymore due to the following error:

In file included from test.cpp:1:
/nix/store/b7hvml0m3qmqraz1022fwvyyg6fc1vdy-gcc-12.2.0/include/c++/12.2.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
   75 | #include_next <stdlib.h>
      |               ^~~~~~~~~~
compilation terminated.

Does anyone know how I can build a working environment for this (quite simple imho) use case?

I did not find a solution for this problem. In my use case, it is a sufficient workaround to only statically link all libraries except for libc. This can be achieved with

gcc [...] -Wl,-Bstatic -llib1 -llib2 -lotherlib -Wl,-Bdynamic

Then, only the gcc package needs be installed, but not the glibc or glibc.static packages.