Why is C++ initial allocation so much larger than C's?

前端 未结 2 1392
时光说笑
时光说笑 2021-01-30 09:44

When using the same code, simply changing the compiler (from a C compiler to a C++ compiler) will change how much memory is allocated. I\'m not quite sure why this is and would

2条回答
  •  天涯浪人
    2021-01-30 10:40

    The heap usage comes from the C++ standard library. It allocates memory for internal library use on startup. If you don't link against it, there should be zero difference between the C and C++ version. With GCC and Clang, you can compile the file with:

    g++ -Wl,--as-needed main.cpp
    

    This will instruct the linker to not link against unused libraries. In your example code, the C++ library is not used, so it should not link against the C++ standard library.

    You can also test this with the C file. If you compile with:

    gcc main.c -lstdc++
    

    The heap usage will reappear, even though you've built a C program.

    The heap use is obviously dependant to the specific C++ library implementation you're using. In your case, that's the GNU C++ library, libstdc++. Other implementations might not allocate the same amount of memory, or they might not allocate any memory at all (at least not on startup.) The LLVM C++ library (libc++) for example does not do heap allocation on startup, at least on my Linux machine:

    clang++ -stdlib=libc++ main.cpp
    

    The heap use is the same as not linking at all against it.

    (If compilation fails, then libc++ is probably not installed. The package name usually contains "libc++" or "libcxx".)

提交回复
热议问题