Vikas
Vikas

Reputation: 179

Why object file size changes for the same code in C and C++

I have written same lines of code in both C and C++ build environment of visual studio 2008 but C code's object file size is 5.5kb and C++ code file size is 6.17 kb. Why is this difference?

Following is the code in both environments:

#include <stdio.h>

struct S
{
    char c;
};
void func()
{
    int i;
    int j;
    printf("%d", i);
}

int main()
{
    struct S s;
    return 0;
}

Upvotes: 5

Views: 527

Answers (3)

wallyk
wallyk

Reputation: 57804

The include file stdio.h has a much more complicated compilation for C++as it probably derives the stdio functions on top of the iostreams functions. For a straight C compile, iostream isn't used. So the object file is smaller in C.


edit

I don't think many of the downvoters understand the question. OP is asking why the object file has increased in size. Not the executable. Not the library.

After looking at stdio.h for VS 2008, I see that the compilation differences for C++ and C are not nearly as dramatic as they are for gcc, which was the basis of my original answer. Still, the namespacing and mangled external symbols make the object file bigger.

Upvotes: -4

Jens Gustedt
Jens Gustedt

Reputation: 79003

Just because your code has different meaning in C and C++.

  • In C++ you declare functions that receive no arguments, in C you declare functions that have an unspecified number of arguments. (Never change the signature of main)
  • function names are mangled in C++
  • functions may throw exceptions in C++
  • executables are linked against different libraries by default
  • because of the lack of initialization of i the call to printf has undefined behavior. Both languages might decide on different strategies to shoot you.

Upvotes: 4

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99725

It links different C runtime libraries in each case. Check here for detailed explanation. For instance, libcmt.lib vs libcpmt.lib.

Upvotes: 5

Related Questions