G++ 将 .hpp 和 .cpp 文件编译为共享库
G++ compiles .hpp and .cpp files differently to shared library
我试图将一个简单的函数编译成共享库对象 (.so)。该函数位于名为 hello.hpp:
的文件中
const char* greet(){
return "hello world";
}
我使用:
g++ -shared -fpic hello.hpp -o hello.so
然后它会创建一个大小为 1.8 MB 的 hello.so 文件。我发现大小不合理,我试图在不更改其内容的情况下将源文件重命名为 hello.cpp。然后我又编译了:
g++ -shared -fpic hello.cpp -o hello.so
这一次,文件只有 7 KB。为什么 g++ 仅仅因为文件名不同而表现不同?我的平台是 Ubuntu 14.04 和 g++ 4.8.2.
简介
即使您指定输出应具有 .so
作为其扩展名,您也没有使用以下命令制作典型的 目标文件 。
g++
,从输入的文件扩展名来看,将创建一个 precompiled header.
g++ -shared -fpic hello.hpp -o hello.so
详细说明
如果你想告诉 g++
把 hello.hpp
当作真的 cpp 文件,你可以通过指定显式输入 -x
.
g++ -shared -fpic -x c++ hello.hpp -o hello.so
原因很简单:g++
根据输入文件名决定你想要什么样的输出(你没有真正指定;--shared
不会那样做) :
我已经以你的例子做了和你一样的事情:
$> 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
区别在于生成的文件类型:
$>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++
如果你只给g++一个header文件,它会认为
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
结果预编译 header 是一个相当大的结构,如您所见。
我试图将一个简单的函数编译成共享库对象 (.so)。该函数位于名为 hello.hpp:
的文件中const char* greet(){
return "hello world";
}
我使用:
g++ -shared -fpic hello.hpp -o hello.so
然后它会创建一个大小为 1.8 MB 的 hello.so 文件。我发现大小不合理,我试图在不更改其内容的情况下将源文件重命名为 hello.cpp。然后我又编译了:
g++ -shared -fpic hello.cpp -o hello.so
这一次,文件只有 7 KB。为什么 g++ 仅仅因为文件名不同而表现不同?我的平台是 Ubuntu 14.04 和 g++ 4.8.2.
简介
即使您指定输出应具有 .so
作为其扩展名,您也没有使用以下命令制作典型的 目标文件 。
g++
,从输入的文件扩展名来看,将创建一个 precompiled header.
g++ -shared -fpic hello.hpp -o hello.so
详细说明
如果你想告诉 g++
把 hello.hpp
当作真的 cpp 文件,你可以通过指定显式输入 -x
.
g++ -shared -fpic -x c++ hello.hpp -o hello.so
原因很简单:g++
根据输入文件名决定你想要什么样的输出(你没有真正指定;--shared
不会那样做) :
我已经以你的例子做了和你一样的事情:
$> 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
区别在于生成的文件类型:
$>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++
如果你只给g++一个header文件,它会认为
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
结果预编译 header 是一个相当大的结构,如您所见。