Reputation: 20126
I have a very small C program which reverses a file. It compiles on windows to an exe
file of size 28,672 bytes.
/O1
and /Os
doesn't seem to make any effect)?BTW - when compiled with gcc
I get around 50Kb file and when compiled with cl
I get 28Kb.
EDIT: Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fi, *fo;
char *file1, file2[1024];
long i, length;
int ch;
file1 = argv[1];
file2[0] = 0;
strcat(file2, file1);
strcat(file2, ".out");
fo = fopen(file2,"wb");
if( fo == NULL )
{
perror(file2);
exit(EXIT_FAILURE);
}
fi = fopen(file1,"rb");
if( fi == NULL )
{
fclose(fo);
return 0;
}
fseek(fi, 0L, SEEK_END);
length = ftell(fi);
fseek(fi, 0L, SEEK_SET);
i = 0;
while( ( ch = fgetc(fi) ) != EOF ) {
fseek(fo, length - (++i), SEEK_SET);
fputc(ch,fo);
}
fclose(fi);
fclose(fo);
return 0;
}
UPDATE:
/MD
produced a 16Kb file.tcc
(Tiny C Compiler) produced a 2Kb file.gcc -s -O2
produced a 8Kb file.Upvotes: 6
Views: 4777
Reputation: 5691
Which libraries do you use? You don't need any libraries for reversing a file in C except the standard lib. Then your executable should be no larger than 2kb.
However if I compile:
int main()
{
return 0;
}
with MinGW, the size of the executable is equal to 48kb. But I haven't used any optimalization flags.
Edit: With the -s flag, it reduces to 7,5 kb.
Upvotes: 1
Reputation: 16724
Check out -s
gcc flag:
-s Remove all symbol table and relocation information from the executable.
A test with small C program that I'm developing:
Without -s
: 120,2 Kib
With -s
: 58,3 Kib
By removing dead code from your executable:
By using -fdata-sections -ffunction-sections
the compiler will put the unused function into separed section that by using -Wl,--gc-sections
will be removed by the `link.
The file size now is: 50,2 Kib
By -O2
do a lot of optimizations, but without increase file size, usually, unlike.
The file size now is: 42,1 KiB
gcc there is too some -O*
to optimization in favor to file size.
Upvotes: 2
Reputation: 70313
#include <stdio.h>
Let it be said by someone who implemented his own version of the stdio functions: They are quite big, and somewhat interdependent. Linking one of them links in several others automatically.
Since this is a one-time cost, and doesn't matter in the scope of big applications, most libraries don't bother much with optimizing this away.
That being said, compiling into a dynamically linking executable instead of a static one is usually the way to go. If you have to have a statically linked executable, you might want to look at one of the libraries optimized for embedded environments, as they are more focussed on small-size optimizations like this.
Upvotes: 3