Home > other >  How to Precompile <bits/stdc .h> header file in ubuntu 20.04?
How to Precompile <bits/stdc .h> header file in ubuntu 20.04?

Time:03-09

Problem Description: Is there any way to precompile the <bits/stdc .h> header file in ubuntu 20.04 like we can do in Windows OS so that I can execute programs faster in my Sublime text editor? (I use the FastOlympicCoding extension for fast execution, but I miss the old way of using an input-output file). I searched everywhere but didn't find any 'layman' approach to do that, so kindly let me know how to solve this problem.

CodePudding user response:

An example creating a precompiled header:

mkdir -p pch/bits &&
g   -O3 -std=c  20 -pedantic-errors -o pch/bits/stdc  .h.gch \
   /usr/include/c  /11/x86_64-redhat-linux/bits/stdc  .h

Check what you got:

$ file pch/bits/stdc  .h.gch
pch/bits/stdc  .h.gch: GCC precompiled header (version 014) for C  

$ ls -l pch/bits/stdc  .h.gch
-rw-r--r-- 1 ted users 118741428  8 mar 23.27 pch/bits/stdc  .h.gch

A program using it:

#include <bits/stdc  .h>

int main() {
    std::vector<int> foo{1, 2, 3};
    for(auto v : foo) std::cout << v << '\n';
}

Example compilation (put -Ipch first of the -I directives):

$ strace -f g   -Ipch -O3 -std=c  20 -pedantic-errors -o program program.cpp 2>&1 | grep 'stdc  .h'
[pid 13964] read(3, "#include <bits/stdc  .h>\n\nint ma"..., 122) = 122
[pid 13964] newfstatat(AT_FDCWD, "pch/bits/stdc  .h.gch", {st_mode=S_IFREG|0644, st_size=118741428, ...}, 0) = 0
[pid 13964] openat(AT_FDCWD, "pch/bits/stdc  .h.gch", O_RDONLY|O_NOCTTY) = 4

CodePudding user response:

Building on Ted's answer, I would actually do something like this (untested):

my_pch.h:

#include <bits/stdc  .h>          // might need to specify the full path here

And then:

g   -O3 -std=c  20 -pedantic-errors -o pch/bits/my_pch.h.gch my_pch.h

And finally, your program would look like this:

#include "my_pch.h"

int main() {
    // ...
}

This means you don't need to put #include <bits/stdc .h> directly in your source files, since that is a bit naughty. It also means you can add other include files to my_pch.h if you want them.

I think, also, it wouldn't cost you anything to put, say, #include <string> after including my_pch.h, and that doing that sort of thing might be wise. If you're ever going to move the code into production you could then recompile it with my_pch.h empty.

  • Related