-1
#include <iostream>

int main() {
    std::cout << "HI";
}

this is the code. after compiling it is 220kb.
I used this command : cl /EHsc main.cpp.
help me reduce the size

GOOD MAN
  • 5
  • 2
  • 3
    Compile with optimization flags. https://learn.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code?view=msvc-170 – kiner_shah Jan 26 '22 at 06:25
  • [Create a C program of size 100 bytes with Visual Studio](https://stackoverflow.com/q/58341734/995714) – phuclv Jan 26 '22 at 06:44
  • The optimization flags are easy enough: `cl /EHsc /W4 /Ox /std:c++latest main.cpp` for speed and `cl /EHsc /W4 /Os /std:c++latest main.cpp` to favor size. Prefer `/Ox` unless you have very special reasons. Notice also how I cranked up your compiler warnings? And set you to compile with the latest C++ Standard? – Dúthomhas Jan 26 '22 at 07:09
  • If you want to know, why it becomes so big: open the iostream header. That's roughly 62k lines of code. Not all of it is used in your binary, sure, but if you are concerned about binary size, other headers (C) might be doing the trick. If you want to reduce size and compile time, you might be interested in the C++20 modules (https://en.cppreference.com/w/cpp/language/modules). – tooEarlyToGetUp Jan 26 '22 at 07:11
  • 1
    @phuclv That does not help OP. [What is the smallest possible Windows (PE) executable?](https://stackoverflow.com/a/45528159/2706707) – Dúthomhas Jan 26 '22 at 07:16

1 Answers1

1

You can get a huge difference by not linking statically to the runtime. In addition to the optimization flags, use /MD to use the runtime DLL.

I get the .exe size down to 11 kB.

And even if you do

#include <iostream>

int main() {
    std::cout << "HI";
    std::cout << "HI";
    std::cout << "HI";
    std::cout << "HI";
}

it is still 11 kB, so it is not growing by 220 kB per source line. :-)

BoP
  • 2,310
  • 1
  • 15
  • 24