Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge C++ files into a single source file

Tags:

c++

I have a c++ project with multiple source files and multiple header files. I want to submit my project for a programming contest which requires a single source file. Is there an automated way of collapsing all the files into single .cpp file?

For example if I had a.cpp, a.h, b.cpp, b.h etc., I want to get a main.cpp which will compile and run successfully. If I did this manually, could I simply merge the header files and append the source files to each other? Are there gotchas with externs, include dependencies and forward declarations?

like image 378
aramadia Avatar asked May 13 '11 17:05

aramadia


3 Answers

I also needed this for a coding contest. Codingame to be precise. So I wrote a quick JavaScript script to do the trick. You can find it here: https://www.npmjs.com/package/codingame-cpp-merge

I used it in 1 live contest and one offline game and it never produced bad results. Feel free to suggest changes or make pull requests for it on github!

like image 192
W. Goeman Avatar answered Oct 07 '22 12:10

W. Goeman


In general, you cannot do this. Whilst you can happily paste the contents of header files to the locations of the corresponding #includes, you cannot, in general, simply concatenate source files. For starters, you may end up with naming clashes between things with file scope. And given that you will have copy-pasted header files (with class definitions, etc.) into each source file, you'll end up with classes defined multiple times.

There are much better solutions. As has been mentioned, why not simply zip up your entire project directory (after you've cleaned out auto-generated object files, etc.)? And if you really must have a single source file, then just write a single source file!

like image 33
Oliver Charlesworth Avatar answered Oct 07 '22 13:10

Oliver Charlesworth


well, this is possiable, I have seen many project combine source files to single .h and .c/.cpp, such as sqlite

but the code must have some limits, such as you should not have static global variable in one of your source codes.

there may not have a generic tool for combine sources.you should write one base on your code.

here is some examples

gaclib source pack tool

like image 1
bowman han Avatar answered Oct 07 '22 11:10

bowman han