How to use multiple source files to create a singl

2019-01-24 06:06发布

I'm using the -c option with g++ to create a bunch of object files, and it's only letting me specify one source file for each object file. I want to have multiple files go into some of them. Is there any way to do this?

标签: c++ object gcc g++
8条回答
叼着烟拽天下
2楼-- · 2019-01-24 06:32

You can use ld -r to combine the objects while keeping relocation information and leaving constructors unresolved:

ld -r -o everything.o object1.o object2.o ...
查看更多
戒情不戒烟
3楼-- · 2019-01-24 06:35

We use -o option to create an object file...... By Default when we compile file using gcc or g++ we get object file named as a.out but we can change its name.... use following to compile file

gcc Filename.c -o NewFilename.out

then to run file you can use ./NewFilename.out

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-24 06:36

Using the solution from Peter Alexander is the main one that comes to mind.

But, keep in mind that by using this method, you'll have to compile your whole sources files each time. When your project grows bigger, compilation time can become a pain.

Furthermore, compiling several files on their own enable the use of the various cores on modern CPUs: each source file will be compiled in its own process, at full speed. Do not under-use the power of the multi cores.

查看更多
smile是对你的礼貌
5楼-- · 2019-01-24 06:38

You can create archive which is a set of object files.

ar mylib.a file1.o file2.o

So effectively you have combined file1.cpp and file2.cpp into mylib.a.

查看更多
你好瞎i
6楼-- · 2019-01-24 06:38

I know you are asking about how to combine .cpp files into one object file. I assume your goal for doing this is to link the combined object at a later time with other individual object files. If this is the case you may be able to use a static or dynamic library instead. For your goals I suggest the dynamic library since you can do a single compile and link step skipping the generation of object files altogether. Using a command such as g++ -shared -fpic file1.cpp file2.cpp file3.cpp -o libtest.so you can combine your .cpp files that need combining into libraries. To compile the library(s) with your individual object files use a command such as g++ -ltest individual1.o individual2.o individual3.o -o myexecutable. In that final linking step I assume libtest.so is in your current directory. If its not in your current directory add a -L flag and the directory libtest.so is in.

查看更多
看我几分像从前
7楼-- · 2019-01-24 06:41

The only solution I know of is to create a separate C++ file, which includes all of the files you want to compile, and compile that. A pretty bad solution, in my mind; generally, you want to increase the granularity of the object files, not reduce it.

The real question, I suppose, is what are you trying to achieve. Why do you want only a single object file?

查看更多
登录 后发表回答