C++: Header issues - c++

I just can't win with headers it seems.
I have a class Log of which has a header Log.h that defines the class Log, and then the Log.cpp implements the methods of Log. I need it available in Main.cpp, so I include Log.h into Main.cpp and I receive the notorious "already defined" errors.
If I take out the header from Main.cpp, I can't use the class.
If I take out the header from Log.cpp, then Log is (obviously) not defined.
I can't win here! What do I do?
EDIT YES, of course I have include guards.
#ifndef LOG_H_
#define LOG_H_
namespace vexal {
#define CCOL_RESET "^[[0m"
#define CCOL_RED "^[[31m"
class Log {
public:
Log();
virtual ~Log();
static void genInstance();
private:
static Log* _inst;
};
}
#endif /* LOG_H_ */
Then the includes are merely #include "Log.h" in both Log.cpp and Main.cpp.

Have you included include guards?
Log.h
#ifndef LOG_H
#define LOG_H
// your code here
#endif

Sounds like you might not have include guards? Try adding to the top of your header file:
#ifndef LOG_HEADER_FILE
#define LOG_HEADER_FILE
And then at the bottom of your header file:
#endif

The issue ended up being the order of which the includes were included. Some includes have to be included before others to avoid redefinition issues.

This is rather vague, but most likely you need some include guards in your header. If you're using MSVC, a #pragma once up the top should do. If not, something standard like:
#ifndef LOG_H_
#define LOG_H_
///Rest of header file
#endif

Related

Multiple definitions when using #ifdef

I am having a problem when compiling: Multiple definitions of "myFunction()"
I will greatly simplify the problem here. Basically, I have 3 files: "main", "header", and "myLibrary".
main.cpp
#include "header.hpp"
int main() { }
header.hpp
#ifndef HEADER_HPP
#define HEADER_HPP
#include "myLibrary.hpp"
// ...
#endif
header.cpp
#include "header.hpp"
// ...
myLibrary.hpp
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
std::string myFunction() { return std::string(); }
#endif
#endif
myLibrary.cpp
#include "myLibrary.hpp"
//...
So, why does the compiler say that I have Multiple definitions of "myFunction()"?
One clue I found: When I take header.cpp and erase the line that says #include "header.hpp", the program compiles without complaining. On the other hand, if I erase myFunction (from myLibrary.hpp) instead, the program also compiles without complains
You are defining the body of the function inside the header file. So every translation unit that you include that header in (in this case, main.cpp and header.cpp) will end up with its own copy of that function body. And when you try to link those multiple units together, you get the "duplicate definition" error.
The function needs to be declared in the hpp file, and defined in the cpp file:
myLibrary.hpp
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
#include <string>
std::string myFunction();
#endif
#endif
myLibrary.cpp
#include "myLibrary.hpp"
#if defined(__unix__)
std::string myFunction()
{
return std::string();
}
#endif
//...
Include guards only prevent the same header from being included twice within the same translation unit, which in practice is usually a single .cpp file. For example, it prevents errors when doing this:
#include "header.h"
#include "header.h"
int main()
{
}
But, more generally, it means that it doesn't matter if you've include a header that has already been included as a dependency of another header.
However, if you have two .cpp files include the same header, and that header contains the definition of a function (such as your myLibrary.hpp) then each .cpp file will have its own definition (the include guard won't help because the header is being included in two separate translation units / .cpp files).
The simplest thing to do is to declare the function in the header, which tells every file that includes your header that the function exists somewhere, and then define it in the .cpp file so that it is only defined once.
You should to define functions in the .cpp files, not in the header files. You declare them in the header files. What you're doing is defining it in the header file, so when it gets included into multiple files, the function is getting duplicated. Cross-file duplicate symbols will throw an error, unless they're static.
myLibrary.cpp:
#include "myLibrary.hpp"
#ifdef(__unix__)
std::string myFunction() { return std::string(); }
#endif
myLibrary.hpp:
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
#include <string>
std::string myFunction();
#endif
#endif

What is the function of include guard in .cpp (not in .h)? [duplicate]

This question already has answers here:
The use of double include guards in C++
(5 answers)
Closed 5 years ago.
Ok, may be this question have answer already but I don't know what keyword to search (most of my searched results are about include guard in .h only, but not in .cpp)
Sometimes I saw in cpp each #include line have a extra include guard (sometimes even the included .h already have the own include guard) like this:
SomeClass.cpp
#ifndef__A__
#include A.h
#endif
#ifndef__B__
#include B.h
#endif
#ifndef__C__
#include C.h
#endif
instead of
SomeClass.cpp
#include A.h
#include B.h
#include C.h
, what is the function of this include guard?
The practice of using include guards in .cpp files was recommended by John Lakos in his book Large-Scale C++ Software Design. I don't know whether any one before him had recommended the practice.
Say you have
A.h:
#ifndef __A__
#define __A__
#include "B.h"
#include "C.h"
// ...
// ...
// ...
#endif
B.h:
#ifndef __B__
#define __B__
// ...
// ...
// ...
#endif
C.h:
#ifndef __C__
#define __C__
// ...
// ...
// ...
#endif
SomeClass.cpp:
#ifndef __A__
#include "A.h"
#endif
#ifndef __B__
#include "B.h"
#endif
#ifndef __C__
#include "C.h"
#endif
When SomeClass.cpp is compiled, the contents of A.h is included. As a by-product of including the contents of A.h, the contents of B.h and C.h are also included. Also, the pre-processor macros __A__, __B__ and __C__ are defined. When the line
#ifndef __B__
is processed, since __B__ is already defined, the next line is skipped.
If SomeClass.cpp had just:
#include "A.h"
#include "B.h"
#include "C.h"
the file B.h has to be opened and processed. The contents of the file will not be included again due to the include guards but the file has to be opened and closed.
By using the first strategy, you avoid the cost of of opening and closing B.h and C.h. For large scale C++ project, John Lakos asserts, the cost is too much. Hence, the recommendation of using include guards even in .cpp files.
It means don't even check the content of header file if the file is already included (symbol_specific_to_header is defined).
In ancient time when opening a file and checking whether contents are already included in header itself was costly (Cost of opening, reading and closing the header was very high) this trick was used to reduce the compile time.
But on modern systems this trick is not required. Though this doesn't cause any harm except the code is repeated and adding cluttering, this would work. Althout adding hashguards in include files is recommended.
This is how the header file looks and are included.
New style:
/* A.h */
#pragma once
...
or
/* A.h */
#ifndef A_H
#define A_H
...
#endif
usage:
#include "A.h"
Or precompiled headers are used.
Old style
The ancient style as mentioned by you:
/* A.h */
#define A_H
...
usage:
#ifndef A_H
#include "A.h"
#endif
It's to protect against including the same header twice.
A.h might look something like this
#define __A__
#include B.h
Without the guards, B.h would be included twice, which could cause errors. So the #ifndef lines in the cpp is just protecting itself from headers including other headers.

Redefinition of function

I have one file example1.cpp with the main function. This file must have #include mylib.h and #include lib.h. File mylib.h also has #include lib.h. When I try to compile this program, the error redefinition xyz function ocurs.
example1.cpp
#include mylib.h
#include lib.h
int main(){
//code
}
mylib.h
#include lib.h
//rest code
You need to put include guards in your header file to prevent it from getting included multiple times during compilation.
#ifndef LIB_H
#define LIB_H
// Actual header file code
#endif
You have to wrap the .h files in #defines to avoid the redifinitions. For example:
#if !defined(_MY_LIB_H_)
#define _MY_LIB_H_
// Add your function definitions here...
#endif // _MY_LIB_H_
You can now include it anywhere and the function definition will be read once. Also note that you can use #ifndef depending on the compiler. VC++ for example, allows "#pragma once" if it's version 10 or higher:
#if _MSC_VER > 1000
#pragma once
#endif
In this case, you don't need to use the #defines explained above.

Visual Studio C++ Headers

I need to create structure like this:
// file main.h:
#pragma once
#ifndef _MAIN_H
#define _MAIN_H
#include <iostream>
#include "first.h"
#include "second.h"
#endif
// -----------------
// file first.h:
#pragma once
#ifndef _FIRST_H
#define _FIRST_H
#include "main.h" // because of using SomeFunction() in first.cpp
int SomeVar; // used in first.cpp
#endif
// -----------------
// file second.h:
#pragma once
#ifndef _SECOND_H
#define _SECOND_H
#include "main.h" // because of using SomeVar in second.cpp
int SomeFunction(); // implemented in second.cpp
#endif
// -----------------
By logic, if main.h will be compiled first, then each of this headers will be included only once and all variables/functions will be defined normally.
For example, this configuration compiled normally in IAR C++ Compiler, if set up in options "preinclude file" (not precompiled) to main.h.
But, in Visual Studio 2010 same structure causes linker errors like:
1>second.obj : error LNK2005: "int SomeVar" (?SomeVar##3HA) already defined in first.obj
1>second.obj : error LNK2005: "int SomeFunction" (?SomeFunction##3HA) already defined in first.obj
I think because of including files in alphabetic order. Apparently pragma- and define-guards are ignored by linker.
Errors can be fixed by additional header and external variables definitions, but this is hard and wrong way.
Question is: What should i do?
int SomeVar; // used in first.cpp
Variables should never be defined in headers. They should be declared with extern:
extern int SomeVar; // used in first.cpp
Then you can actually define them in "first.cpp" with int SomeVar;.
Also, "first.h" does not need to include "main.h". Headers should only include files if the definitions in that header absolutely need the contents of those files. The definitions in "first.h" do not need anything in "main.h". Therefore, it should not include it.
If "first.cpp" needs to include something from "second.h", then it is the responsibility of "first.cpp" to include it.
In the header file use extern keyword as:
//first.h
extern int SomeVar; //extern tells the compiler that definition is elsewhere
Then in .cpp file define it and use it:
//first.cpp
int SomeVar; //definition is here
As for SomeFunction, have you defined it header file itself? Re-check it. :-)

Why it's valid to include a header file twice in c++?

#include "DLLDefines.h"
#include "DLLDefines.h"
The above actually passed compilation, but why?
Well, it's legal because it has to be legal. Because you often include the same header multiple times without even realizing it.
You might include two headers in a .cpp file, each of which include a number of files, some of which might be included by both.
For example, all the standard library headers (say, string or vector for example) are probably included in most of your headers. So you quickly end up with the same header being indirectly included multiple times in the same .cpp file.
So in short, it has to work, or all C++ code would fall apart.
As for how it works, usually through include guards. Remember that #include just performs a simple copy/paste: it inserts the contents of the header file at the #include site.
So let's say you have a header file header.h with the following contents:
class MyClass {};
now let's create a cpp file which includes it twice:
#include "header.h"
#include "header.h"
the preprocessor expands this to:
class MyClass {};
class MyClass {};
which obviously causes an error: the same class is defined twice. So that doesn't work. Instead, let's modify the header to contain include guards:
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
Now, if we include it twice, we get this:
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
#ifndef HEADER_H
#define HEADER_H
class MyClass {};
#endif
And this is what happens when the preprocessor processes it:
#ifndef HEADER_H // HEADER_H is not defined, so we enter the "if" block
#define HEADER_H // HEADER_H is now defined
class MyClass {};// MyClass is now defined
#endif // leaving the "if" block
#ifndef HEADER_H // HEADER_H *is* defined, so we do *not* enter the "if" block
//#define HEADER_H
//
//class MyClass {};
//
#endif // end of the skipped "if" block
So, the end result is that MyClass got defined only once, even though the header was included twice. And so the resulting code is valid.
This is an important property of header files. Always define your headers so that it is valid to include them multiple times.
It depends on the header file; there is no language restriction on multiple includes of the same file.
Some files are designed to be included multiple times (e.g. <assert.h> can be included multiple times to turn 'on' and 'off' assert).
Many files are safe to be included multiple times because they have include guards, others are not and should be included only once in a translation unit or even a program.
include has nothing to do with the C or C++ language. It is a directive to the preprocessor to bring in a file. The preprocessor doesn't care what file is brought in and it shouldn't. It might be perfectly acceptable to do this:
void Foo::SomeFunc(int cond)
{
switch (cond) {
case kThisCase:
#include "longFirstCase.h"
break;
case kSecondCase:
#include "longSecondCase.h"
break;
case kThirdCase:
#include "longFirstCase.h"
#include "longSecondCase.h"
break;
}
}
I have seen the same file included several times as a configuration mechanism as well.
Granted, there are a number of ways to factor that example that are better, but the point is that there may be perfectly good reasons why you would want to and therefore no restriction on the use.
Probably you have some #define in DLLDefines.h around your code that prevents it from being included twice.
#ifndef DLLDEFINES_H
#define DLLDEFINES_H
// your code
#endif
As long as the multiple inclusion of header files do not violate ODR (One definition Rule) $3.2, the code is well-formed.
It's called an include guard.
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct foo {
int member;
};
#endif
Quote from Wikipedia:
In the C and C++ programming languages, an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the #include directive. The addition of #include guards to a header file is one way to make that file idempotent.
See link above for more information.
DLLDefines.h may also have #pragma once at the
top, #pragma once ensures that file gets included only once.