ENIGMA
ENIGMA

Reputation: 115

G++ compiles .hpp and .cpp files differently to shared library

I was trying to compile a simple function into shared library object (.so). The function is in a file named hello.hpp:

const char* greet(){
  return "hello world";
}

I use:

g++ -shared -fpic hello.hpp -o hello.so

Then it creates a hello.so file of size 1.8 MB. I found the size unreasonably big, I tried to rename the source file to hello.cpp without changing its content. Then I compiled again:

g++ -shared -fpic hello.cpp -o hello.so

This time, the file is only 7 KB. Why g++ behaves differently just because the file name is different? My platform is Ubuntu 14.04 and g++ 4.8.2.

Upvotes: 4

Views: 10670

Answers (2)

Marcus Müller
Marcus Müller

Reputation: 36462

The reason is simple: g++ decides, based on the input filename, what kind of output you want to have (you didn't really specify; --shared doesn't do that):

I have taken your example and did the same as you did:

$> ls -l cpp/ hpp/
cpp:
total 12K
-rwxr-xr-x. 1 marcus marcus 7.8K Mar 22 12:27 hello.so
-rw-r--r--. 1 marcus marcus   48 Mar 22 12:26 libtest.cpp

hpp:
total 1.9M
-rw-r--r--. 1 marcus marcus 1.9M Mar 22 12:27 hello.so
-rw-r--r--. 1 marcus marcus   48 Mar 22 12:26 libtest.hpp

The difference lies in the type of file that was generated:

$>file {c,h}pp/hello.so
cpp/hello.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=7a74d02c517bbb196fb8e517e85a0bba6349020d, not stripped
hpp/hello.so: GCC precompiled header (version 014) for C++

If you just give g++ a header file, it will think

huh? That's a header. You don't compile headers, they don't contain code -- hm, probably the programmer wants to use this header in a lot of places, so he asks me to pre-parse it and generate a fast-to-read syntax tree

The resulting precompiled header is a rather largish structure, as you can see.

Upvotes: 1

Filip Roséen
Filip Roséen

Reputation: 63882

Introduction

Even though you specify that the output shall have .so as its extension, you aren't making a typical object file with the command below.

g++, judging from the input file extension, will create a precompiled header.

g++ -shared -fpic hello.hpp -o hello.so

Elaboration

If you want to tell g++ to treat hello.hpp as if it really was a cpp-file, you can do so by specifying the explicit type to -x.

g++ -shared -fpic -x c++ hello.hpp -o hello.so

Upvotes: 8

Related Questions