Precompiled headers with GCC - c++

How can I get precompiled headers working with GCC?
I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on Cygwin GCC 3.4.4 and using 4.0 on Ubuntu.

I have definitely had success. First, I used the following code:
#include <boost/xpressive/xpressive.hpp>
#include <iostream>
using namespace std;
using namespace boost::xpressive;
// A simple regular expression test
int main()
{
std::string hello("Hello, World!");
sregex rex = sregex::compile( "(\\w+) (\\w+)!" );
smatch what;
if( regex_match( hello, what, rex ) )
{
std::cout << what[0] << '\n'; // Whole match
std::cout << what[1] << '\n'; // First capture
std::cout << what[2] << '\n'; // Second capture
}
return 0;
}
This was just a Hello, World! program from Boost Xpressive. First, I compiled with the -H option in GCC. It showed an enormous list of headers that it used. Then, I took a look at the compile flags my IDE (Code::Blocks) was producing and saw something like this:
g++ -Wall -fexceptions -g -c main.cpp -o obj/Debug/main.o
So I wrote a command to compile the Xpressive.hpp file with the exact same flags:
sudo g++ -Wall -fexceptions -g /usr/local/include/boost/xpressive/xpressive.hpp
I compiled the original code again with the -H and got this output:
g++ -Wall -fexceptions -H -g -c main.cpp -o obj/Debug/main.o
! /usr/local/include/boost/xpressive/xpressive.hpp.gch
main.cpp
. /usr/include/c++/4.4/iostream
.. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h
.. /usr/include/c++/4.4/ostream
.. /usr/include/c++/4.4/istream
main.cpp
The ! means that the compiler was able to use the precompiled header. An x means it was not able to use it. Using the appropriate compiler flags is crucial. I took off the -H and ran some speed tests. The precompiled header had an improvement from 14 seconds to 11 seconds. Not bad, but not great.
Note: Here's the example. I couldn't get it to work in the post.
BTW: I'm using the following g++:
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3

Firstly, see the documentation here.
You compile headers just like any other file but you put the output inside a file with a suffix of .gch.
So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called stdafx.h.gch anytime you include stdafx.h
Example:
stdafx.h:
#include <string>
#include <stdio.h>
a.cpp:
#include "stdafx.h"
int main(int argc, char**argv)
{
std::string s = "Hi";
return 0;
}
Then compile as:
> g++ -c stdafx.h -o stdafx.h.gch
> g++ a.cpp
> ./a.out
Your compilation will work even if you remove stdafx.h after step 1.

The -x specifier for C++ precompiled headers is -x c++-header, not -x c++. Example usage of PCH follows.
pch.h:
// Put your common include files here: Boost, STL as well as your project's headers.
main.cpp:
#include "pch.h"
// Use the PCH here.
Generate the PCH like this:
$ g++ -x c++-header -o pch.h.gch -c pch.h
The pch.h.gch must be in the same directory as the pch.h in order to be used, so make sure that you execute the above command from the directory where pch.h is.

Call GCC the same way as if you call it for your source file, but with a header file.
E.g.,
g++ $(CPPFLAGS) test.h
This generates a file called test.h.gch.
Every time GCC searches for test.h, it looks first for test.h.gch and if it finds it it uses it automatically.
More information can be found under GCC Precompiled Headers.

I have managed to get precompiled headers working under gcc once in the past, and I recall having problems then as well. The thing to remember is that gcc will ignore the file (header.h.gch or similar) if certain conditions are not met, a list of which can be found on the gcc precompiled header documentation page.
Generally it's safest to have your build system compile the .gch file as a first step, with the same command line options and executable as the rest of your source. This ensures the file is up to date and that there are no subtle differences.
It's probably also a good idea to get it working with a contrived example first, just to remove the possibility that your problems are specific to source code in your project.

Make sure to -include your_header.h
This is how I precompiled and used bits/stdc++.h collection.
Code
#include <bits/stdc++.h>
Then I located the lib by compiling my file with -H and looking at output
g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable
where I saw
. /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h
So I made a new directory bits inside of current one and copied stdc++.h from there.
Then I ran
g++ bits/stdc++.h -O3 -std=c++14 -pthread
which generated bits/stdc++.gch
Normally I compiled my code via
g++ sol.cpp -O3 -pthread -lm -std=c++14 -o executable
, but I had to modify that to
g++ sol.cpp -include bits/stdc++.h -O3 -pthread -lm -std=c++14 -o executable
as it only resolved to .gch file instead of .h with -include bits/stdc++.h
That was key for me. Other thing to keep in mind is that you have to compile *.h header file with almost the same parameters as you compile your *.cpp. When I didn't include -O3 or -pthread it ignored the *.gch precompiled header.
To check if everything's correct you can measure time difference via comparing result of
time g++ sol.cpp ...
or run
g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable
again and look for header paths and if you now get ! before library path, for example
! ./bits/stdc++.h.gch
....

A subtle tip about the file extension that tripped me up, because I wasn't paying close enough attention: the .gch extension is added to the precompiled file's full name; it doesn't replace .h. If you get it wrong, the compiler won't find it and silently does not work.
precomp.h => precomp.h.gch
Not:
precomp.h => precomp.gch
Use GCC's -H to check if it's finding/using it.

Related

How to use libraries and headers in C++ with MinGW?

I want to use OpenGL GLEW library. I have the binary downloaded and its folder is in the folder with my .cpp file. My .cpp file uses #include <eglew.h>.
How should I format my command for MinGW to compile my .cpp file? Do I compile with the .lib file like g++ -L./path/to/lib/file.lib test.cpp -o test or do I do something else like link to the header files g++ -I./path/to/headers test.cpp -o test?
To better understand things maybe it's better to split compiling and linking steps.
If you get errors then you will also know in which step the problem occurs.
I'm assuming you have the following folders/files:
/path/to/eglew/include/GL/eglew.h
/path/to/eglew/lib/libglew32.a
Compiling:
g++ -Wall -c -o test.o test.cpp -I/path/to/eglew/include/GL
Linking:
g++ -o test.exe test.o -L/path/to/eglew/lib -lglew32
Though I would expect to see #include <GL/eglew.h> in which case the linker include flag should be -I/path/to/eglew/include.

Why am I getting "undefined reference to main"

I am a very new to programming and have a very basic question that may be answered in other threads however I think they are far too advanced for me to understand how. I have actually found many answers so far on this site but this is the first problem that forced me to create an account and ask.
Anyway i am running a very basic example program on linux mint 18.3. Now I have seen this exact code work on a machine with windows 8 I believe so I was wondering if that could be the problem. I have created a class and when i plug in my object then build and run I get:
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o||In function _start':|
(.text+0x20)||undefined reference tomain'|
This is the entire code:
#include <iostream>
#include "Gladius.h"
using namespace std;
int main()
{
Gladius io;
return 0;
}
Thats it very basic. here is the .h
#ifndef GLADIUS_H
#define GLADIUS_H
class Gladius
{
public:
Gladius();
};
#endif // GLADIUS_H
and the .cpp for the class.
#include "Gladius.h"
#include <iostream>
using namespace std;
Gladius::Gladius()
{
cout << "The Gladius is a short sword" << endl;
}
I know this seems extremely simple but I am just learning to code and i have been looking all over for an explanation why this isn't working yet I see it work on another pc exactly as is. Anyway any explanation would be greatly appreciated.
Here is what i found in command line If this answers your questions about what was in the cmd.
g++ -Wall -fexceptions -g -std=c++11 -Wall -I -c /home/gator/Documents/Spartan1/Gladius.cpp -o obj/Debug/Gladius.o
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function _start':
(.text+0x20): undefined reference tomain'
collect2: error: ld returned 1 exit status
Know the compiler options(gcc/g++ compiler):
-c : Compile and assemble, but do not link
-o file : Place the output into file
So when you run
g++ filename.cpp -o executable_name
, you generate an application which can be executed.
The problem is you are compiling, assembling as well as linking when you are trying to compile "Gladius.cpp" and compiler is trying to search for main() definition.
So in your case, the compilation steps would be:
First compile "Gladius.cpp" and generate object file "Gladius.o":
g++ -Wall -fexceptions -g -std=c++11 -c Gladius.cpp
Next compile "main.cpp" and generate object file "main.o":
g++ -Wall -fexceptions -g -std=c++11 -c main.cpp
Generate executable by linking "main.o" and "Gladius.o"
g++ -Wall -fexceptions -g -std=c++11 -o main main.o Gladius.o
Now you can run "main":
./main
Your compiler's command line contains -I -c sequence.
This -I option "swallows" your -c option. -I requires an additional argument, which is an include directory name. You failed to supply that argument, which is why -I assumes that -c that follows it is the directory name. So that -I consumes that -c.
The compiler never sees that -c. Without -c it assumes that you want to compile and link your program. Since Gladius.cpp does not have main in it, you get the error at linking stage.
Here 's a simple demo of the same problem: http://coliru.stacked-crooked.com/a/8a37cd3e90a443e2
You need to figure out why you have an orphaned -I in your command line.
If you are compiling this code using a command line like:
g++ -Wall -Wextra -Werror -O gladius.cpp -o output.exe
then make sure that you include all the .cpp files (not .h files) that contain code that your program needs.
g++ -Wall -Wextra -Werror -O gladius.cpp main.cpp -o output.exe
I explain this to beginners all the time as each .cpp being a bag of Lego's in a kit. You need all the bags that came with the box in order to build the kit. If you omitted main.cpp (or the file that contains main) then you will get the linker error that you are currently getting.
What command are you using to compile, link, and then execute? It should look something like
$ g++ main.cpp gladius.cpp -odemo
$ ./demo
check your command line for linking step.. You may forgot file with main as input, or you had forgot output file name after -o (and masked main.o in result)
I had this very kind of problem myself, and though it may not be the conventional, "proper" solution, I simply renamed the ".c" file to ".cpp", and it all worked.
After all, I was compiling both c and c++ together with a c++ compiler (recommended by the library), and the c code already had the proper c++ #extern flags (see here for more on that).
Also related:
C++ Error: undefined reference to `main'
Including C Code in C++
Why do you need an explicit `-lm` compiler option
Compilation on Linux - In function '_start': (.text+0x20): undefined reference to 'main'

Geany, g++ and SDL errors in compilation

So, I was following a simple C++ with SDL tutorial for linux but i encounter some errors on my way.
First of all I'm using Geany and i downloaded the corresponding SDL2 libs, here is the thing:
in my project folder there is a main.cxx file, which i open with geany as i mentioned before:
I included this libraries:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
First i encountered a pelculiar error, compilation performs sucessfully but when it comes to build i got this error:
main.cxx: undefined reference to `SDL_Init'
After searching a bit i found out that i had to add the tag -lSDL to my geany build options so they would end up being somethinf like this:
Compile:
g++ -Wall -c -lSDL "%f"
Build:
g++ -Wall -o -lSDL "%e" "%f"
But there is a problem, now when I execute the build command i get a:
G ++: error: main: There is no such file or directory
Why am i getting this error, am I including a wrong library or g++ has problems with .cxx files?
I already tried converting between .cxx and .cpp.
Thanks in advance.
g++ -Wall -c -lSDL2 "%f"
There is absolutely no need to specify libraries during compilation phase. Remove -lSDL.
g++ -Wall -o -lSDL2 "%e" "%f"
It invokes compiler, implies linking (no -c or other operation-specific flags), and sets output file name to -lSDL2. That is, linker will output resulting binary in a file named -lSDL2 in current working directory. Then, when it comes what files to link, it goes main, which supposed to be -o main, but since you've broken flags order it is now just ordinary file name that linker will try to link into resulting binary. It so happens that this file doesn't exist.
Long story short, make correct linking line - g++ -o "%e" %f -lSDL2 (libraries comes last, library order is also important).

How do I link multiple files without the use of a makefile?

For example, I'm given carModels.cpp, carModels.h, carType.in, manufacturers.h, manufacturers.o, and lastly my own file tester.cpp. How would I go about linking all of these using g++ in a Linux terminal? Would I have to create any additional ".o" files? I'm supposed to assume that the given files already work. Multiple lines in terminal are fine, I just I want a clear understanding of it. (I'm coming from a C++ IDE that I didn't really care for.)
Compile each source file to its own object file:
g++ -I . -c carModels.cpp -o carModels.o
g++ -I . -c tester.cpp -o tester.o
Now link all object files together:
g++ carModels.o tester.o manufacturers.o -o outputname
Consider adding more options like -O3, -std=c++11, -Wall, etc. as needed.
you can do this in two steps, first compile to *.o files,
gcc -c your.cpp other.cpp .....
then link them
gcc -o you_out_put_name the_object_files.o ...
In a single line, that would be just g++ -o tester *.cpp *.o. GCC will sort everything out. In particular, the *.h files are referenced via #include "" statements in the .cpp files.

g++ makefile, include error, no such file or directory

I am trying to include the following headers:
#include <libs/serialization/example/portable_binary_iarchive.hpp>
#include <libs/serialization/example/portable_binary_oarchive.hpp>
These files are located in a path like:
/home/nobody/boost_1_45_0/libs/serialization/example/portable_binary_iarchive.hpp
In my Makefile, I have added:
-I/home/nobody/boost_1_45_0/libs
However, when I compile, I get the error messages like:
error: libs/serialization/example/portable_binary_iarchive.hpp: No such file or directory
Can anybody tell me what I am doing wrong here? I am also including boost libraries like
#include <boost/archive/binary_oarchive.hpp>
However, to get those, it is sufficient to do in my Makefile:
-I/usr/include/boost
Why doesn't this work for the headers in the other location? How should I change my Makefile? The first statement current looks like this:
test: test.o
g++ -O3 -ffast-math -funroll-loops -ansi -pedantic-errors -L/usr/lib -lboost_filesystem -lboost_serialization -lboost_iostreams -lz -I/usr/include/boost -I/home/nobody/boost_1_45_0/libs -o test test.o
To get
#include <libs/serialization/example/portable_binary_iarchive.hpp>
from directory
/home/nobody/boost_1_45_0/libs/serialization/example/portable_binary_iarchive.hpp
your Makefile needs
-I/home/nobody/boost_1_45_0
Notice that I omitted the /libs from the end. That's because your #include directive already lists that directory.
As for your second example, is the file you want at this location:
/usr/include/boost/boost/archive/binary_oarchive.hpp
^^^^^ (repeated boost here)
If not g++ is likely defaulting to /usr/include as the search space for
#include <boost/archive/binary_oarchive.hpp>
Ie., your
-I/usr/include/boost
is useless to the compiler.