I_like_python
I_like_python

Reputation: 67

How small can I make a clang executable?

I'm just testing to see how small I can make this C++ code

#include <iostream>
using namespace std;

int main() {
    cout << "hi";
}

using this zsh command:

g++ test.cpp -Os -g -o main

but the smallest I can make it is 52 Kb, so is there any way to make it even smaller?

Upvotes: 2

Views: 2479

Answers (2)

chubercik
chubercik

Reputation: 775

Using your code and compiler flags with g++ 11.2, I get a 35,8kB executable (different result could be explained by using a different compiler version or target system).

  1. Removing the -g flag (debugging symbols for GDB GNU Debugger or LLDB Clang/LLVM Debugger) brings the output file's size down to 16,3kB.
  2. You can modify your code without changing its functionality in the following way (16,0kB):
#include <stdio.h>

int main(){
    fputs("hi", stdout);
    return 0;  // doesn't change the output, only here for completeness sake
}
  1. Using clang to compile above code further reduces output executable's size to 15,9kB.

  2. Adding the -s flag (strip debug information): 14,5kB (same results using both clang and g++ 11.2)

Comparison table (best results in bold):

code compiler flags size step
original g++ 8.5.0 -Os -g 38 496 B
-Os 16 304 B
-Os -s 14 464 B
g++ 11.2.0 -Os -g 35 848 B 0
-Os 16 320 B 1
-Os -s 14 464 B
clang 11.0.1 -Os -g 30 736 B
-Os 16 304 B
-Os -g 14 552 B
clang 13.0.0 -Os -g 29 312 B
-Os 16 232 B
-Os -s 14 488 B
modified g++ 8.5.0 -Os -g 18 552 B
-Os 16 000 B
-Os -s 14 464 B
g++ 11.2.0 -Os -g 18 616 B
-Os 16 000 B 2
-Os -s 14 464 B
clang 11.0.1 -Os -g 16 720 B
-Os 15 960 B
-Os -s 14 528 B
clang 13.0.0 -Os -g 16 640 B
-Os 15 888 B 3
-Os -s 14 464 B 4

Upvotes: 7

kimstik
kimstik

Reputation: 1899

As mentioned, you should to strip symbols by "-s"

By using "-m32" you may define 32-bit code generation, which should be a bit more compact.

Finally, I suggest using the UPX compressor.

gcc -s -Os -m32 main.c

gcc 12.2.0 + upx = 6144 bytes win32 executable

With some additional effort you may go under 1k footprint range:

Upvotes: 2

Related Questions