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. :-)
Related
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
I have declared a global variable in header.h and included that header in source.cpp and main.cpp but linker is giving error
Source.obj : error LNK2005: "int globalVariable" (?globalVariable##3HA) already defined in Main.obj
GlobalVariableAndLinkageIssue.exe fatal error LNK1169: one or more multiply defined symbols found
header.h
int globalVariable;
source.cpp
#include "header.h"
main.cpp
#include"header.h"
void main() {}
Move the declaration to a .cpp file. You can use a declaration in a header file by using:
extern int globalVariable; // declaration in header - can have as many as you need
But the .cpp file should have the definition:
int globalVariable; // definition in .cpp - only need one across all your files
C and C++ use textual pre-processor to include headers, this is basically a text insertion, not a smart module system as in some languages. By including it as you were, you are creating multiple definitions, one per .cpp file.
As a matter of good practice, you need to get used to using include guards to protect against multiple nested includes (though it would not solve your current issue). If using Visual C++, you can use #pragma once or to use a portable solution wrap your header code in:
#ifndef _INCLUDE_FOO_H_
#endif
To create a global variable, you should do the following. Note that in the header, we mark the variable as extern, and we actually create the object in a cpp file.
header.h
extern int globalVariable;
header.cpp
#include "header.h"
int globalVariable;
main.cpp
#include "header.h"
int main() {}
Put global variable in some .c or .cpp file, so that it can be defined only once and refer in header file using extern
for example,
header.h
extern int globalVariable;
header.cpp
int globalVariable = 0;
source.cpp
#include "header.h"
main.cpp
#include"header.h"
int main() {
return 0;
}
Because BOTH sources #include your header, and thus it is DEFINED twice.
In such situation,it is common to use some #define as follows:
//header.h
#ifdef DEFINE_VARS
#define DEFINE_OR_DECLARE
#else
#define DEFINE_OR_DECLARE extern
#endif
DEFINE_OR_DECLARE int globalVariable;
//main.cpp
#define DEFINE_VARS
#include "header.h"
...
//header.cpp
#include "header.h"
...
I'm using Xcode to build a C++ project.
But I don't understand the error message:
"Apple Mach-O linker command failed with exit code 1"
I found that #include is the reason.
I have two .cpp file which include a same .h file. If I remove #include of one, it will be build successfully.
Other header files are fine expect the header file described above. I already used "ifndef".
#ifndef include guards only work at the level of the translation unit (usually a single source file).
If you define the same object twice in two translation units, that won't be fixed by include guards but the linker will complain bitterly when you try to combine the two object files into a single executable.
I suspect your situation is akin to:
hdr.h:
#ifndef HDR_H
#define HDR_H
void rc(void);
int xyzzy;
#endif
prog1.c:
#include "hdr.h"
#include "hdr.h"
int main (void) { rc(); return xyzzy; }
prog2.c:
#include "hdr.h"
void rc(void) { xyzzy = 0; }
In a situation like that, the include guard will prevent the header being included twice in prog1.c but it will still be included in both prog1.c and prog2.c, meaning that each will have a copy of xyzzy.
When you link them together, the linker will not like that.
The solution is to not define things in headers but to merely declare them there, leaving the definition for a C file:
hdr.h:
#ifndef HDR_H
#define HDR_H
int rc(void);
extern int xyzzy; // declare, not define
#endif
prog1.c:
#include "hdr.h"
#include "hdr.h"
int main (void) { rc(); return xyzzy; }
prog2.c:
#include "hdr.h"
int xyzzy; // define
int rc(void) { xyzzy = 0; }
Declarations are things like function prototypes, extern variables, typedefs and so on (simplistically, things that declare something exists without actually creating an "object").
Definition are things that create "objects", like non-extern variables and so on.
You need to track down what "object" is being defined twice (the linker output should have something like doubly-defined symbol 'xyzzy') and then make sure it's not defined in the header.
Can't understand what is a problem here:
I have got main.cpp file where I am including:
#include "lexan.h"
...
The lexan.h file:
#ifndef _LEXAN_
#define _LEXAN_
enum Statements ...
//some function prototypes
...
struct TokensList {
Statements statement;
std::string value;
struct TokensList *next;
};
struct TokensList *tokens = NULL;
#endif _LEXAN_
In lexan2.h:
#include "lexan.h"
// and some function prototypes
The problem is that I get the link error 2005:
1>lexan2.obj : error LNK2005: "struct TokensList * tokens" (?tokens##3PAUTokensList##A) already defined in lexan.obj
1>main.obj : error LNK2005: "struct TokensList * tokens" (?tokens##3PAUTokensList##A) already defined in lexan.obj
Where is my mistake? I thought the
#ifndef _LEXAN_
#define _LEXAN_
in the lexan.h file would protect me from such linking problems.
You are creating struct TokensList * tokens in the header file lexan.h and then including the header in both lexan.cpp & lexan2.cpp which violates the One Definition Rule(ODR).
Note that, header guards prevent including the same header in the same Translation Unit. When you create a variable in the header file, a copy of the variable with the same name gets created in every translation unit where you include the header. This leads to multiple same named variables in your project which the linker complains about.
Solution:
If you need to share it across files, you need to use extern.
How to use extern?
Have a look at:
What are extern variables in C?
How to correctly use the extern keyword in c?
You are violating the one definition rule, as hinted in comments.
Header files should declare variables; they should (almost) never define variables. Your header is defining the variable tokens, which means that only one source file in a given program can use the header, which is not what was intended.
I suggest taking a look at What are extern variables in C? for an extensive (possibly too extensive) discussion of how to handle variables in headers.
But the fundamental rule is:
Do not define variables in headers; only declare them.
Of course, that assumes that the global variable is necessary. When you can, avoid them. But when they are necessary, the header should declare, not define, the variable.
Include guards only stop you from processing the same header twice per translation unit (source file).
Let's say you have a header, X.h, which has include guards:
// x.h
#ifndef X_H
#define X_H
// x.h stuff
#endif
You also have A.h and B.h, each of which include X.h:
// a.h
#ifndef A_H
#define A_H
#include "x.h"
// a.h stuff
#endif
// b.h
#ifndef B_H
#define B_H
#include "x.h"
// b.h stuff
#endif
Then we have j.cpp and k.cpp:
// j.cpp
#include "a.h"
#include "b.h"
// j.cpp stuff
// k.cpp
#include "a.h"
#include "b.h"
// k.cpp stuff
Here the include guards prevent x.h from being processed twice within j.cpp, likewise in k.cpp. But x.h is still included twice, once for each translation unit. So if // x.h stuff was this:
int myGlobalInt; // x.h stuff
Although you prevent j.cpp (and k.cpp) from defining this variable twice, each still has defined it once. At link time, the linker finds them both and complains.
What you want — other than avoiding global variables, which you should try to do — is this:
extern int myGlobalInt; // x.h stuff
Now each translation unit gets told "there exists a myGlobalInt somewhere", and you can explicit define it in a single translation unit of your choosing.
Also, don't use those kinds of header guards; names beginning with an underscore followed by a capital, as well as those beginning with two consecutive underscores are reserved.
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.