Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a C program smaller

Tags:

c

I have a very small C program which reverses a file. It compiles on windows to an exe file of size 28,672 bytes.

  • What is the best approach for reducing the file size?
  • Are there any tools that can tell me what takes the most space? (included libraries)
  • Is this size normal for such a simple program?
  • What compiler flags should I use to reduce file size (/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:

  • Compiling with /MD produced a 16Kb file.
  • Compiling with tcc (Tiny C Compiler) produced a 2Kb file.
  • Compiling with gcc -s -O2 produced a 8Kb file.
like image 237
zenpoy Avatar asked Dec 21 '22 13:12

zenpoy


1 Answers

Try to compile it using tcc: http://bellard.org/tcc/ .

like image 158
alinsoar Avatar answered Dec 24 '22 02:12

alinsoar