Cannot include header files correctly - c++

I'm having an issue where I'm adding some includes
#include <stdio.h>
#include <unordered_map>
#include <mysql.h>
Using this command to compile,
g++ -Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient -I/usr/include/mysql -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX -I/usr/include/ -I/usr/include/c++/4.5/bits/ main.c -o program
When i remove the .h on MySQL and stdio it says that it cannot find them, yet it works find on the unordered_map. Wtf?

Some standard library headers are named for example "string", "vector" etc. You will find file "unordered_map" in your include dir, but you won't find file "mysql", only "mysql.h".

Since the ages of C, most headers have had an extension which is typically .h, and they directly correspond to files in the system. In C++ the standard explicitly specifies certain library components as having include directives not including any extension, such as <unordered_map>. These library includes aren't even required to correspond to a file, just that they provide the required interface when included. By contrast, mysql.h and stdio.h and real files that must be included by exact name.
In the case of stdio.h the C++ library defines an include <cstdio> that includes all the features of C's stdio.h but puts them in the std namespace instead of global (which was the only option in C).

The file name extension is not optional! The reason you can say
#include <unordered_map>
instead of
#include <unordered_map.h>
is because the file is actually called "unordered_map", no extension.
C++ does have the cstdio header which wraps C's stdio.h so you can include that instead; but as for MySql.h, I don't know whether they ship such a replacement.

C++ omits the ".h" from it's system header files to differentiate them from the C header files. Detailed here under the section titled "C++ Headers for the Standard C Library"

Related

Multiple includes with #include in C++

I have a question regarding the #include preprocessor directive in C++.
In my program I would like to include a header file from another directory. For this I have used the full path, example:
#include "full/path/to/my/header.hpp"
Now it turns out that header.hpp itself has an include (let's say #include "otherheader.hpp". During compilation, the compiler complains that it cannot find this other header.
What is the best way to handle this problem, considering the fact that I also don't want to write the full path for every header file, especially including those that are only needed "further down the tree"?
You should use your compiler's -I option.
Example with g++:
g++ -I full/path/to/my/
Then in your code you can simply put:
#include "header.hpp"
More information on search path.
Most compilers allow you to specify the root for additional include directories when compiling. For example, in Visual C++ you specify the -I flag. It's also the same for gcc. For example:
compiler -Ipath/to/headers myfile.c
Don't specify full path to includes. Specify include directories to the compiler instead and then just #include <foo> knowing that foo will be found in /some/path/foo because you told the compiler to search /some/path/ for includes. For many compilers this is done with the -I option.

How to make C/C++ compiler to look for headers in a user specified path

I'm using a library written by others which is kinda based on C for C++ usage -I think-. All inclusions used inside the headers or source files are in the form <> instead of "" even though they are not standard library files. My compiler doesn't recognize them and returns error "file not found"
An example of the problem is inside the following header:
#ifndef _ga_ga_h_
#define _ga_ga_h_
// Make sure that we get the configuration into each of the galib components
// that will be used.
#include <ga/gaconfig.h>
// These are the headers for all of the genetic algorithm classes.
#include <ga/GASimpleGA.h>
#include <ga/GASStateGA.h>
#include <ga/GAIncGA.h>
#include <ga/GADemeGA.h>
#include <ga/GADCrowdingGA.h>
// Here we include the headers for all of the various genome types.
#include <ga/GA1DBinStrGenome.h>
#include <ga/GA2DBinStrGenome.h>
#include <ga/GA3DBinStrGenome.h>
#include <ga/GABin2DecGenome.h>
I include that header inside my program using #include "ga.h" but it is very hard to change inside every header/source file in the library.
Is there a way to make the compiler use <> as if they were ""?
I tried adding the paths to "Addition include directories"from Project properties (I'm using Visual Studio), Many inclusions' errors disappeared but around 30 persisted. The strange thing is that they are in a file called "c1xx" but i don't have that file!!
thanks,
The definition is somewhat that <> is used for "system" header files, usually found in locations like /usr/include (on Unix-like systems) and "" is used for local header files. When you compile your code, you can indicate the location of additional directories containing header files e.g. using the -I option when using GCC. Check your compiler's documentation for the setting needed
So, e.g. on Linux and GCC, if your "ga" directory is in /usr/local/include/ga, you would use cc -I /usr/local/include.
This indeed looks like a problem of telling the compiler where to look for the included header files. As mentioned in the other answers, when you do a #include <header.h>, header.h must be in one of the include search paths - either the system includes, or the additional paths that you are telling the compiler to look for headers. In Linux/g++ (as mentioned in the other answers here), you do that by passing in the the additional search paths in the -I flag. The compilation command would look something like:
g++ -I/additional/header/search/path -o a.out your_file.cpp
Since you are using visual studio and the MSVC compiler, the equivalent would be the /I flag, and the compilation command would look something like:
CL /I\additional\header\path your_file.cpp
I am assuming you are using Visual Studio - you can also configure that from the project properties. Go to Configuration Properties > C/C++ > General and modify Additional Include Directories. Refer these for more info:
Setting C++ compiler and build properties
Additional include directories
First about the difference between <header> and <file>. The standards (both C and C++) only specifies that
#include <header>
includes an header named header and that
#include "file"
includes a source file named file, if none is found an header named file is included instead.
What are headers and how they differ from source files is left to the implementation. In practice they are files as well. So #include <header> is looking for a file in some places, #include "file" is looking for a file in some other places and if not found at the same places as for #include <file>.
AFAIK all compilers
are able to search for source files in the directory of the file containing the include directive
are able to be given a list of directories to search for headers before their default search path.
ISTR that Visual C++ is also searching for a source file in the directories of files indirectly including it. (I can't confirm currently if my memory is good; that behavior is AFAIK unachievable with other compilers so I never relied on it and -- by luck? -- it never resulted in a different behavior for my programs).
Obviously that behavior is more or less customizable. For instance with g++ is possible to:
disable the search of a source file in the directory of the file containing the include directive (with -I-, note that -I- is deprecated since gcc 4.0 -- 2005 -- when -iquote has been introduced and there is no non-deprecated way to achieve this)
to add a list of directories to search for source files and not for headers (with -iquote and it's an effect of -I- as well)
to give a list of directories to search for headers after the default list of directories (with -idirafter)
to give a list of directories to search for headers which are processed specially (with -isystem; less warnings are given for constructs in those files which help when using the "treat warnings as errors" flags, they aren't considered as dependencies with -MM and -MMD which usually is a nuisance)
Now for your problem. The library has been visibly designed to be used by adding the directory containing the directory ga to the include path. That should be enough as I'm unaware of any compiler modifying its search path for headers depending on how the file including the header has been included.
Note that c1xx is probably the name of the compiler executable, not the name of a file trying to include another (again, I'm not in position to ensure that's the case now, but compare with cc1plus which is the name of the compiler for GCC -- g++ is a driver handling several things and executing cc1plus to handle the compilation of C++ code)
If you do on the command line:
echo | gcc -v -E -x c++ -
You will get an output with the default include directories for C++. Those are the built in system's include search paths.
If you compile with g++ -I/some/dir -o foo foo.cpp, you are adding an additional include search path (/some/dir) to the compilation.
Headers in the above locations can be found by include directives like #include <header>. #include "header" directives can also find headers in those locations, but they are more relevant for the following case.
When you do #include "header", your compiler will first try to find "header" relative to the directory of foo.cpp if it includes it, despite foo.cpp directory being in search paths or not. If it doesn't find it there, it will try to look up in the include search paths. So this one is more relevant for headers that are more tied to a specific .cpp file and you don't want additional include search paths added to the compilation, or if you prefer to use include directives with relative paths.
So if you use #include <header>, header must be in some of the include search paths, system or /some/dir from -I flag. If header is relative to foo.cpp, but not in search paths, compilation will fail.
If you use #include "header" and header is not in any of the include search paths, it can still be found relative to foo.cpp location.

How a compiler knows from a header file, that a source file exists somewhere?

I just started to learn C/C++, but I'm a bit confused. I often see the #include preprocessor directive, with a header file argument:
#include <stdio.h>
#include <iostream.h>
#include "windows.h"
#include <math.h>
But sometimes the .h is missing:
#include <iostream>
I already know, that the header file contains the signatures of the functions only, and some preprocessor commands. But when and how does the compiler include the math functions, if I include math.h?
If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
When you install the compiler, the standard header and library files are also installed into well-known locations. For example, on a Linux or Unix system, the standard headers are typically installed under /usr/include or /usr/local/include and the standard libraries are typically installed under /usr/lib or /usr/local/lib.
When you #include the header file, the compiler will look for it in different places depending on whether you use the angle brackets (#include <stdio.h>) or quotes (#include "myfile.h"). For example, if you include a header file in angle brackets, gcc will search for that header in the following directories:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
If you include a header file with quotes, gcc will first search the current working directory, then additional directories as specified by command-line options, and finally the standard include paths above.
Most compilers allow you to specify additional include paths as arguments to compile command, such as
gcc -o executable-name -I /additional/include/path source-files
But sometimes the .h is missing:
#include <iostream>
This is the C++ convention1; C++ standard headers do not have the .h extension, I guess to make it look more object-oriented than it really is (that is, you can pretend you're importing the class directly, rather than including the text of the file that describes the class).
I already know, that the header file contains the signatures of the functions only, and some preprocessor commands. But when and how does the compiler include the math functions, if I include math.h?
The implementations of the math functions are typically kept in a separate library (code that's already been compiled and archived into a single binary file); depending on the compiler, the math library may or may not be automatically linked into the executable. For example, gcc does not automatically link in any math library functions, even if you include the math.h header file. You have to explicitly include the math library as part of the build command:
gcc -o executable-name command-line-options source-files -lm
With gcc, the convention is that -lname links in a library named libname.a2. The standard math library file is named libm.a, so -lm tells gcc to link in the machine code that's contained within libm.a.
Like the standard headers, the compiler will search for the standard libraries in well-known locations. You can specify additional search paths for libraries that aren't part of the standard installation, like so:
gcc -o executable-name command-line-options source-files -L /additional/library/path -ladditional-library
If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
You can put the files pretty much anywhere you want; you'll specify where they are as part of the build command. So, say you're creating a new library named mylib. You create a new directory under your home directory:
mkdir ~/mylib
cd ~/mylib
Then you create and edit your source files and headers:
cd ~/mylib
vi mylib.h
vi mylib.c
To build mylib as a static library, do the following:
cd ~/mylib
gcc -c mylib.c
ar libmylib.a mylib.o
So when you're done, the directory ~/mylib contains the following:
libmylib.a
mylib.c
mylib.h
mylib.o
To use the functions collected in mylib in a program, you'd specify the header and library include paths as part of the compile command:
gcc -o executable-name command-line-options source-files -I ~/mylib -L ~/mylib -lmylib
So, if you include "mylib.h" in another program, this will tell the compiler to search for that header in ~/mylib, and it will tell the linker that the libmylib.a library will be found under ~/mylib.
In a real-world situation you'd handle all of the builds with makefiles instead of building everything by hand. You'd also probably set it up so that as part of the build process, all the headers that anyone else would need to use your library would be copied to a separate include subdirectory, and the library would be written to a separate lib subdirectory, so you could distribute your library without exposing your source code. In that case, the build command above would look more like:
gcc -o executable-name command-line-options source-files -I ~/mylib/include -L ~/mylib/lib -lmylib
1. This hasn't always been the case; the earliest implementations of C++ used iostream.h, vector.h, etc. I'm not sure exactly when that convention changed, but it's been a while.
2. Actually, I'm not sure anymore if this is a gcc convention or a *nix convention; the two have been joined at the hip for so long it's hard to remember sometimes.
Actually, the compiler doesn't know anything about other source files, it only knows about the current translation unit. It's the job of the linker to take all translation units and link them together with the libraries to create the executable program, and it's the linker that will resolve all definitions and that notice missing function definitions.
Traditionally, working with C or C++ is a four step process:
Edit files
Compile source files into object files
Link object files and libraries to generate the executable program
Run the program.
The preprocessor is usually built into the compiler, so preprocessing and compiling is only a single step.
As for the "missing" .h, none of the C++-only standard library header files have that extension.
Standard Template Library headers, such as < algorithm > include source code for the template functions, which get instantiated at compile time, based on the template type(s) involved in source code calls to template functions.
A library is a collection of object files in a single library file. The linker normally only includes the object files needed to satisfy the references to functions or data to build the program, not the entire library file. The exception to this is a dynamic link library, since all of that library will be loaded (if not already loaded) at program load time.
The compiler has default locations for headers using < > and using " ". The headers using " ", can include relative or absolute paths. The relative path may vary depending on the tool set.
Re
” How a compiler knows from a header file, that a source file exists somewhere?
Generally, how a compiler locates header files, or if they are files, depends on the compiler.
But usually one or more of the following mechanisms are used:
The compiler knows its own program location, and can look for include directories for standard headers, relative to that location. g++ does this.
The compiler can be configured with paths to include directories in one or more environment variables. E.g. g++ uses CPATH (among others), and Visual C++ uses INCLUDE (and possibly more).
The compiler can accept include directory paths as command line options. Typically this is -I or with Visual C++, alternatively /I.
The compiler can be configured via a configuration file in a well known location. For example, g++ uses a specs file.
The compiler can accept one or more configuration files as command line options. E.g. Visual C++ accepts so called "response files", and g++ accepts specs files, although with slightly different semantics than the general configuration specs file.
Possibly there are more mechanisms in use, but the above are the most common ones.
Re
” But when and how does the compiler include the math functions, if I include math.h?
It doesn't.
The whole of the standard library is linked in regardless of what headers you include. Depending on the quality of the implementation the unused parts of the standard library are then discarded.
When you use a 3rd party library you will generally have to explicitly link with that library, in addition to including one or more of its headers. The Visual C++ compiler supports #pragma directives that can be placed in headers and serve to automatically direct the linker. But this is not standardized, and e.g. g++ does not support that automagic mechanism.
Re
” If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
Essentially you have free reins, you can do it any way you want. Which is problematic because users of a C++ library have to deal with different conventions and tools for each library, to the extent of using a different OS to "configure" things. However, nowadays it's popular to employ CMake for libraries with separate compilation, which helps to reduce the DIY problems.
A nice alternative is to create a header only library, with all the code in headers. Large parts of Boost are header only. The advantage is that it's very easy to use, no configuration or toolset adaption or whatever, but with currently popular 1950's build technology it can cause longer build times.

Compiling a .CPP using GCC

how do I compile a .c or .cpp file using GCC?
I need to include some standard libraries (fstream, string, iostream) - how do I do this?
For clarification, here:
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include"ocgenerator.h";
#include"structures.h";
#include"util.h";
#include"util2.h";
using namespace std;
(my .h files are in the same directory as the src file)
If I use the command:
gcc src.cpp -o src.o
I get a lot of errors: memcpy, atoi, atol, strncmp, etc, ... "are not declared in this scope". What should I add to the command?
edit: Or is it a scope thing, and do I have to add std:: to all those functions?
memcpy and strncmp are declared in <cstring>, atoi and atol in <cstdlib>. Just include these headers to bring in their declarations.
Side notes :
No semicolon after preprocessor directives, including #include "".
No using namespace std;, especially not in headers !
(Why is "using namespace std" considered bad practice?)
Since you're building a C++ project, don't forget to link with the standard library via -lstdc++, or use g++ which forwards it to the linker for you.
Note that with GCC you don't have to prefix standard C functions with std:: (as they are also declared in the global namespace), but you should anyway for your code to be standard-compliant.
The cplusplus site helps out. If you search for a specific function, on the top you will find the necessary references for the code to compile:
http://www.cplusplus.com/reference/cstdlib/atol/
You can even check in the URL. In this case, you need 'cstdlib'.
Regarding the compiler, there are several available, g++ is a good option.
I also suggest creating a makefile for automating the building process, because it becomes an headache when your codebase grows.
For any library function you use in your code, read the man page for that function to see which header declares it, and #include that header in any source file that uses the function.
For example, man memcpy shows the memcpy(3) man page (the (3) refers to section 3 of the manual; use man 3 memcpy to specify the section).
NAME
memcpy - copy memory area
SYNOPSIS
#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);
...
memcpy is part of the C standard library, and is declared in <string.h>. For C++ you can use <string.h>, but it's probably better to use <cstring>, which puts the function name in the std namespace. In general, each standard C header <foo.h> is duplicated as a C++ header <cfoo>.
I get a lot of errors: memcpy, atoi, atol, strncmp, etc,
memcpy and strncmp are declared in <cstring>. atoi and atol are <cstdlib> (or in <string.h> and <stdlib.h> if you're programming in C rather than in C++).
And be sure to use the g++ command, not the gcc command, to compile C++ source. They both invoke the same compiler (gcc compiles C++ code if the source file name ends in .cpp), but the g++ command adds some options that are needed for C++.

Use stdlib functions without including stdlib.h

I am compiling a large number of files which use srand() and rand() without including stdlib.h.
I'm aware that this is bad practice but, as I cannot change the files that I am compiling, inserting the necessary include statement in each file is not an option.
How can I configure my compiler to allow implicit inclusion of stdlib functions? Also, is there a way to implicitly use the std namespace in the same way?
Edit: Using g++
Edit: Looks like this is the answer (to the first part, at least). To compile a file as if stdlib.h is included, use the option -include stdlib.h
As you've now mentioned that you're using GCC, you can just use the -include flag. Other compilers probably have equivalents.
If you don't have such a flag for your compiler, you could use the following not-entirely-serious solution, that should work nevertheless:
nice.cc
#include <stdlib.h>
#include "naughty.cc"
(where naughty.cc is the original source file).
Of course, with a suitable build system, you could automatically generate the nice wrapper files.
Since you are already embracing bad practice, how about:
cat > foo.c << EOF
#include <stdlib.h>
#include "file-to-compile.c"
EOF
${CC} foo.c
You're using GCC, so you can use the -include option (from the manual):
Process file as if #include "file" appeared as the first line of the primary source file.
For example:
g++ -include stdlib.h foo.c