Why use precompiled headers (C/C++)? - c++

Why use precompiled headers?
Reading the responses, I suspect what I've been doing with them is kind of stupid:
#pragma once
// Defines used for production versions
#ifndef PRODUCTION
#define eMsg(x) (x) // Show error messages
#define eAsciiMsg(x) (x)
#else
#define eMsg(x) (L"") // Don't show error messages
#define eAsciiMsg(x) ("")
#endif // PRODUCTION
#include "targetver.h"
#include "version.h"
// Enable "unsafe", but much faster string functions
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
// Standard includes
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <direct.h>
#include <cstring>
#ifdef _DEBUG
#include <cstdlib>
#endif
// Standard Template Library
#include <bitset>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
#include <string>
#include <numeric>
// Boost libraries
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/scoped_array.hpp>
//Windows includes
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "FILETIME_Comparisons.h"
#include <shlwapi.h>
#include <Shellapi.h>
#include <psapi.h>
#include <imagehlp.h>
#include <mscat.h>
#include <Softpub.h>
#include <sfc.h>
#pragma comment(lib, "wintrust.lib")
#pragma comment(lib,"kernel32.lib")
#pragma comment(lib,"Psapi.lib")
#pragma comment(lib,"shlwapi.lib")
#pragma comment(lib,"imagehlp.lib")
#pragma comment(lib,"Advapi32.lib")
#pragma comment(lib,"Shell32.lib")
#pragma comment(lib,"Sfc.lib")
#pragma comment(lib,"Version.lib")
// Crypto ++ libraries
#ifdef _DEBUG
#pragma comment(lib,"cryptlibd.lib")
#else
#pragma comment(lib,"cryptlib.lib")
#endif
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <md5.h>
#include <sha.h>
// String libraries
#include "stringUnicodeConversions.h"
#include "expandEnvStrings.h"
#include "randomString.h"
#include "getShortPathName.h"
// Regular Expression Libraries
#include "fpattern.h"
// File Result Record
#include "unixTimeToFileTime.h"
#include "fileData.h"
// Writer
#include "writeFileData.h"
// Criteria Structure System
#include "priorities.h"
#include "criterion.H"
#include "OPSTRUCT.H"
#include "regexClass.H"
#include "FILTER.h"
// Sub Programs Root Class
#include "subProgramClass.h"
// Global data
#include "globalOptions.h"
// Logger
#include "logger.h"
// Console parser
#include "consoleParser.h"
// Timeout handler
#include "timeoutThread.h"
// Zip library
#include "zip.h"
#include "unzip.h"
#include "zipIt.h"
// Scanner
#include "mainScanner.h"
#include "filesScanner.h"
// Sub Programs
#include "volumeEnumerate.h"
#include "clsidCompressor.h"
#include "times.h"
#include "exec.h"
#include "uZip.h"
// 64 bit support
#include "disable64.h"

In C/C++, the #include mechanism is a textual copy of the file specified into the current file. Headers include other headers (which include yet other headers), so when you do a #include, it could be adding tens of thousands of lines of C++ into each cpp file (or cxx, c, whatever), all of which need to be compiled each time. This can be a severe bottleneck for large projects.
Precompiled headers speed this up by compiling each header once, then including that compiled state into the cpp they are included in.

It compiles a lot quicker. C++ compilation takes years without them. Try comparing some time in a large project!

Re: your current usage, if you have a target with a very large number of files, it may still be faster to use PCH in that way - try switching them off to find out. It depends: if you have a lot of headers of your own, and you change them only infrequently, and you have a very large number of source files that you change much more frequently, then your PCH usage will cut rebuild times.
But normal advice is to only put things in PCH that never change, because there is a certain overhead to producing the PCH itself. If you trigger that off with every rebuild (by constantly tweaking one of your headers), using PCH may make the rebuild slower.

So you don't have to compile them every time you build your project. They're used for system headers that aren't going to change.

It speeds up compilation.
When you're including headers from other projects, you don't expect to change them. If you put these into a precompiled header, then that code will not have to be recompiled when you make changes to your source code. This reduces repetitive compilation of unchanged code, speeding up compile time.

Related

CLion C++ fatal error: 'process.h' file not found

When I use CLion on a Mac to compile C++ code for highlight removal in a single image, there is an error:
Please help me fix it.
#ifndef QX_CVPR09_CTBF_BASIC_H
#define QX_CVPR09_CTBF_BASIC_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <numeric>
#include <vector>
#include <process.h>
#include <direct.h>
#include <io.h>
#include <time.h>
#include <string>
#include <memory.h>
#include <algorithm>
#include <functional> // For greater<int>()
#include <iostream>
#if _MSC_VER > 1020 // if VC++ version is > 4.2
using namespace std; // std c++ libs implemented in std
#endif
#define QX_DEF_PADDING 10
#define QX_DEF_THRESHOLD_ZERO 1e-6
class qx_timer {public: void start(); float stop(); void time_display(char *disp=""); void fps_display(char *disp=""); private: clock_t m_begin; clock_t m_end;};
It's a part of my code. The full code is too long.
process.h
process.h is a C header file which contains function declarations and
macros used in working with threads and processes. Most C compilers
that target DOS, Windows 3.1x, Win32, OS/2, Novell NetWare or DOS
extenders supply this header and the library functions in their C
library. Neither the header file nor most of the functions are defined
by either the ANSI/ISO C standard or by POSIX.
Depends on which platform you compile and what standard you use. If you are on linux or compile with c99/ansi standard then this header will probably just not be available (which might be your error)

Why do I get so many `LNK2005` errors despite using `#ifndef #define #endif` code blocks in my .h files?

I have 21 files as shown here in the picture:
The following 35 functions are declared in lines 364-411 of util.h inside a
#ifndef FlagUtil
#define FlagUtil
#endif
code block:
Create_Pix, Remove_Pix, my_round, edit_error, check_file, check_dir,
read_config, write_config, write_envi_config, my_randomize, my_random,
my_eps_random, cadd, csub, cmul, cdiv, cpwr, cconj, cimg, crel, cmod, cmod2,
angle, cplx_sinc, PolTypeConfig, init_file_name, memory_alloc, PrintfLine,
CreateUsageHelpDataFormat, CreateUsageHelpDataFormatInput,
init_matrix_block, block_alloc, CheckFreeMemory, CheckFreeMemoryWin32,
CheckFreeMemoryLinux
The following 30 functions are declared in lines 99-135 of util_block.h inside a
#ifndef FlagUtilBlock
#define FlagUtilBlock
#endif
code block:
read_matrix_int, read_matrix_float, read_matrix_cmplx, write_matrix_int,
write_matrix_float, write_matrix_cmplx, read_matrix3d_float,
read_matrix3d_cmplx, write_matrix3d_float, write_matrix3d_cmplx,
read_block_matrix_int, read_block_matrix_float,
read_block_matrix_matrix3d_float, read_block_matrix_cmplx,
write_block_matrix_int, write_block_matrix_float,
write_block_matrix_matrix3d_float, write_block_matrix_cmplx,
write_block_matrix3d_float, write_block_matrix3d_cmplx, read_block_S2_avg,
read_block_S2_noavg, read_block_S2T6_avg, read_block_SPP_avg,
read_block_SPP_noavg, read_block_TCI_avg, read_block_TCI_noavg,
read_block_S2_TCIelt_noavg, read_block_SPP_TCIelt_noavg, average_TCI
The following 35 functions are declared in lines 106-149 of util_convert.h inside a
#ifndef FlagUtilConvert
#define FlagUtilConvert
#endif
code block:
S2_to_C3elt, S2_to_C4elt, S2_to_T3elt, S2_to_T4elt, S2_to_T6elt,
SPP_to_C2elt, SPP_to_T2elt, S2_to_SPP, S2_to_IPP, S2_to_C2, S2_to_C3,
S2_to_C4, S2_to_T2, S2_to_T3, S2_to_T4, S2_to_T6, SPP_to_C2, SPP_to_T2,
SPP_to_IPP, SPP_to_T4, C2_to_IPP, C2_to_T2, T2_to_C2, C4_to_T4, C4_to_C3,
C4_to_T3, C4_to_C2, C4_to_IPP, T4_to_C4, T4_to_C3, T4_to_T3, C3_to_T3,
C3_to_C2, C3_to_IPP, T3_to_C3, T6_to_C3
And the contents of the file PolSARproLib.h is:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#ifdef _WIN32
#include <dos.h>
#include <conio.h>
#endif
/* ROUTINES DECLARATION */
#include "util.h"
#include "util_block.h"
#include "util_convert.h"
#include "graphics.h"
#include "matrix.h"
#include "processing.h"
#include "statistics.h"
#include "sub_aperture.h"
#include "my_utils.h"
And the contents of the file PolSARproLib.c is:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#ifdef _WIN32
#include <dos.h>
#include <conio.h>
#endif
/* ROUTINES DECLARATION */
#include "util.c"
#include "util_block.c"
#include "util_convert.c"
#include "graphics.c"
#include "matrix.c"
#include "processing.c"
#include "statistics.c"
#include "sub_aperture.c"
#include "my_utils.c"
I’ve placed those 21 files in a folder named Static Project and I’ve created the PolSARproLib.lib file as follows, my machine is a Win 10x64 one: (here I’ve uploaded this project):
The files graphics.obj, matrix.obj, my_utils.obj, PolSARproLib.lib, PolSARproLib.obj, processing.obj, statistics.obj, sub_aperture.obj, util.obj, util_block.obj, util_convert.obj are created in the Debug folder of the project without any error, but some warnings like:
1>graphics.obj : warning LNK4006: _write_header_bmp_8bit already defined in
PolSARproLib.obj; second definition ignored
I have created a folder named Arii and placed the following 22 files in the subfolder \Arii\lib
I have also the file arii_anned_3components_decomposition.c placed in the folder Arii:
Now I create the project arii_anned_3components_decomposition in the folder Arii as follows (here I’ve uploaded the project)
In the following 2 pictures, you see the configuration of the project. Again, I should say that I’m working on a Win 10x64 machine
External library is added to the project as follows:
Properties>C/C++>General>Additional Include directories
I enter the path to the folder in which header files .h are placed
Properties>Linker>General>Additional library directories
I enter the path to the folder in which .lib files are placed
In
Properties>Linker>Input>Additional Dependencies
I’ve entered name of those needed .lib files:
Here is the beginning (before main function) of the file arii_anned_3components_decomposition.c:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "omp.h"
#ifdef _WIN32
#include <dos.h>
#include <conio.h>
#endif
/* ROUTINES DECLARATION */
#include "../lib/PolSARproLib.h"
Now I build the solution:
And unfortunately I get 104 errors. 100 of them is about multiple definition of the functions in util.h, util_convert.h, util_block.h (those functions are listed in the beginning of question)
Errors 1-100 are alike:
1>PolSARproLib.lib(PolSARproLib.obj) : error LNK2005: _C3_to_T3 already
defined in PolSARproLib.lib(util_convert.obj)
Here I’ve uploaded the error and warning file.txt
I really don’t understand why am I getting these errors regarding that the code blocks #ifndef #define #endif have been used in the
code?
As stated by CoryKramer, we don't need the file PolSARpro.c, in fact we should never #include .cpp or .c files and this is what has been done in that file:
The contents of the file PolSARproLib.c is:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#ifdef _WIN32
#include <dos.h>
#include <conio.h>
#endif
/* ROUTINES DECLARATION */
#include "util.c"
#include "util_block.c"
#include "util_convert.c"
#include "graphics.c"
#include "matrix.c"
#include "processing.c"
#include "statistics.c"
#include "sub_aperture.c"
#include "my_utils.c"
So, in order to get rid of all those 100 LNK2005 errors, simply place these 20 files (Omit PolSARproLib.c) in a folder
And do the next steps as stated in the question for creating and building the static library project PolSARproLib.lib file and for creating and building the console application project arii_anned_3components_decomposition.exe file.

Compile errors when attempting to link <boost\property_tree\json_parser.hpp>

I have the following "includes" file in my project.
#pragma once
//glm
#include <glm\glm.hpp>
#include <glm\ext.hpp>
#include <glm\gtc\matrix_transform.hpp>
//glew
#include "GL\glew.h"
//glfw
#define GLFW_DLL
#include "GLFW\glfw3.h"
//libpng
#include <png.h>
//std
#include <stdio.h>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <list>
#include <memory>
#include <iostream>
#include <fstream>
#include <assert.h>
//boost
#include <boost\filesystem.hpp>
#include <boost\property_tree\json_parser.hpp> /* problem */
//mandala
#include "types.h"
#include "type_traits.h"
#include "hash.h"
#include "macros.h"
When I include <boost\property_tree\json_parser.hpp>, I get many errors indicating that I'm redefining APIENTRY such as this one:
1>c:\program files (x86)\windows kits\8.0\include\shared\minwindef.h(130): warning C4005: 'APIENTRY' : macro redefinition
I'm perplexed as to why this is happening. I've tried to suppress the minwindef.h file from being processed by putting #define _MINWINDEF_ before the include statement but to no avail. Has anyone else encountered this or have any idea how I can properly include this boost library?
NOTE
Since youd did neither update your question to reflect the changes to the includes you made, nor provide the whole warning message, I can only guess:
You still have glfw.h included before the boost lib that includes the WinAPI header. Because when I just google for "APIENTRY redefinition", I get this SO question as first result, including the answer: Put the WinAPI header (or the boost header includign them) before the glfw.h include.
You may want to include also ptree.
#include <boost/property_tree/ptree.hpp>

What is causing ld: duplicate symbol

ld: duplicate symbol StringFunctions::intToString(int) in
/Build/Intermediates/Y36PJC-mrvikmil.build/Debug/Y36PJC-mrvikmil.build/Objects-normal/x86_64/ServerSocket.o and
/Build/Intermediates/Y36PJC-mrvikmil.build/Debug/Y36PJC-mrvikmil.build/Objects-normal/x86_64/main.o
for architecture x86_64
function StringFunctions::intToString(int) is in StringFunctions.h
includes from main.cpp:
#include <iostream>
#include <string>
#include "Exception.h" //does not include anything more
#include "ServerConsole.h"
/*
which includes ServerSocket.h which includes ClientSocket.h which includes StringFunctions.h
AND
ServerSocket.h includes SocketException.h which includes StringFunctions.h
*/
includes from ServerSocket.cpp:
#include <iostream>
#include <string>
#include "InvalidPortException.h" //does not include anything more
#include "SocketException.h" //which includes StringFunctions.h
#include "ClientSocket.h" //which includes SocketException.h which includes StringFunctions.h
#include "StringFunctions.h" //StringFunctions.h
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
I believe that as long as i have things in .h files, i can include pretty much anything anywhere...
All my files has include guard (#ifndef ... #define ...)
Please help.
You have to define the function as inline or move its implementation to a cpp file. Otherwise it will exist in both objects and C++ won't know which one (despite them being identical) to link.
Include guards will avoid having the same header multiple times in the same code file/object. However they won't avoid having the same piece of code in multiple object files, as each one is create on its own with all defines reset.

C++ header files for UDP in Windows?

I have a linux applications which sends data over UDP protocol. It uses these header files:
#include <stdio.h>
/* standard C i/o facilities */
#include <stdlib.h>
/* needed for atoi() */
#include <unistd.h>
/* defines STDIN_FILENO, system calls,etc */
#include <sys/types.h> /* system data type definitions */
#include <sys/socket.h> /* socket specific definitions */
#include <netinet/in.h> /* INET constants and stuff */
#include <arpa/inet.h> /* IP address conversion stuff */
#include <netdb.h>
#include <string.h> /* for string and memset etc */
/* gethostbyname */
#include <iostream>
#include <fstream>
#include <opencv/highgui.h>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
I want to make a WIndows version of my app. But some of the above header files do not work in WIndows, especially those for UDP.
Which header files should I substitute them for in Windows (Visual Studio 2010)?
UPDATE:
Ok, so my header now looks like this:
#include <iostream>
#include <fstream>
#include "stdafx.h"
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <winsock2.h>
I get this error when trying to compile (and many other similar errors):
Error 13 error C2011: 'fd_set' : 'struct' type redefinition c:\program files (x86)\microsoft sdks\windows\v7.0a\include\winsock2.h 132 1 Client
At compile-time, you need to use Winsock2.h instead of the Unix headers.
At link-time, include ws2_32.lib to provide linkage to the required system DLL.
Comment out the include files that are "missing"
or put them into the following:
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN 1
#include <winsock2.h>
#include <windows.h>
#else
// unix includes here
#endif
You don't need most of those includes. The only file you will need is winsock2.h and link with ws2_32.lib.
So, for all networking stuff, just include winsock2.h.
You want to #include winsock2.h. One peculiarity, you need to #include before including anything else, including :
#include <winsock2.h>
#include <windows.h>