_Na2Th's blog

By _Na2Th, history, 18 months ago, In English,

This is a tip for C++ programmers who use the bits header to include every library from C++.

#include <bits/stdc++.h>

Even more so with C++11, it may take some time for it to compile on your machine. I speak by experience: it took me more than 4s to compile every single time. This would drive me crazy during contests.

I know it works on linux with gcc. I would guess it works on any unix with gcc, but I really don't know.

The solution I offer here is to precompile the headers, and avoid processing every header file every time.

I'll explain by example, showing how I would prepare for the upcoming contest, round 429.

The first thing to do is to make the folder I'll leave my code in, and copy the template file I have into it.

mkdir cf429
cp temp.cpp cf429/

The template goes something like

#include "bits/stdc++.h"
#define mt make_tuple
using namespace std;

int main(){
}

Note the use of #include "bits/stdc++.h" instead of #include <bits/stdc++.h>. This is important, since it makes the compiler first look for the local copy, and only afterwards try to look in the libraries. This is what ensures that the code will run on the Online Judge and take advantage of the precompiled local version in my machine.

Then I would need to find where the header is. It is possible to do so by compiling a program which includes the library with the -H flag. I'll just compile my template.

g++ -H temp.cpp

The first file is the header we are looking for. In my machine it was on /usr/include/c++/7.1.1/x86_64-pc-linux-gnu/bits.

So I can just copy this file into the directory I am going to use during the competition and precompile it. I do it in a way that I do not have to change the header, so that I can submit the file normally.

To be able to do so, create a bits directory, copy the file into it, and compile the header with the same flags you use. In the code below, remember to change the directory to the one you found with the g++ -H command.

mkdir bits
cp /usr/include/c++/7.1.1/x86_64-pc-linux-gnu/bits/stdc++.h bits/
cd bits
g++ -std=c++11 stdc++.h

Now, just to ensure that I'll will have the same flags, I use a Makefile.

cd ..
echo "CXXFLAGS = --std=c++11" > Makefile

and done! I can just wait for the contest to begin, and compile my programs much faster with a simple make A.

Note that you can freely modify the local header copy, removing some stuff that you deem useless, to make it compile even faster. Also, you can then just copy this local version into the directories used in the competition. With this special local version, it is quite easy even to make a script that does the set up mentioned above.

Read more »

 
 
 
 
  • Vote: I like it  
  • +52
  • Vote: I do not like it