I have a header file which begins with
#if !defined(__GLOBAL_H)
#define __GLOBAL_H
then some code followed by
#endif
The code contains only function declarations, some include of other header files and the a few template functions. However, the problem occurs when I add one single line of code. I get linker error that the function I added has already been defined in an object file. I'm using Visual Studio 2012 Premium as compiler. I have tried to remove any existing function from the header file, and that also goes through the compiler. On the other hand, if I add any new line that may be new to the compiler, it refuses to compile saying it has already been defined. Does anyone have any clue what might be wrong or can I have stumbled upon an error inside the compiler itself? (which I highly doubt)
Edit:
The solution was to declare the function the the header file, but to define it in the CPP file. But the real issue was that when I include a header file for returning an object of the type declared in the header file, it does not compile. It many of the errors "Missing ; in front of *" which was types declared in other header files.
Although you haven't shown use any code or error messages, I'm guessing that there are function definitions (including the code for the function body), not just declarations, in the header.
These must either be declared inline, which allows them to be defined in more than one translation unit; or moved into a single source file, leaving just the declaration in the header, so they are only defined on one translation unit.
The "One Definition Rule" says that (unless they are inline) functions may only have one definition in the program.
Also, your include guard shouldn't begin with an underscore, nor contain a double underscore; names like that are reserved.
Adding non-inlined function definitions to header files is generally bad. The compiler will generate code for the function in every file it is included in resulting in the redefintion error you are encountering. Instead you should declare the function in the header and place the definition in a source file (.cpp).
Global.h
#if !defined(__GLOBAL_H)
#define __GLOBAL_H
void somefunction(); // <-- declaring the function.
#endif
SomeSource.cpp
#include "Global.h"
// Here is where define the function
void somefunction()
{
}
Related
This question already has answers here:
Multiple definition of a function error, even when using #if guard clauses
(5 answers)
Closed 6 years ago.
I initialised some arrays in a file called Fares.cpp in my project. When I try using #include "Fares.cpp" in my main.cpp file (where the main code for the project is) in Dev-C++, the compiler gives an error saying “multiple definition”. I don't know what to do, please help.
I don’t know much about macros, extern etc.
Try including "Fares.h" instead of "Fares.cpp". #include is usually used to include header files which usually contain variable declarations and function prototypes. Check this link for more info: http://www.learncpp.com/cpp-tutorial/19-header-files/
Traditionally, .c and .cpp files are related to single compile unit (module, etc.), processed by compiler separately. Include meant to add files called "header files" or "include files" to the file scope, making declarations, inline functions definitions and type definitions in them being available to syntax analyzer of compiler.
Declarations include:
Function declaration
Template declaration
Explicit template instantiation
Explicit template specialization
Namespace definition
Linkage specification
Attribute declaration (attr ;) (since C++11)
Empty declaration (;) (since C++11)
To avoid multiple definition of same classes or functions, header files must use #ifndef blocks as "brackets"
// beginning of file.h
#ifndef SOME_UNIQUE_ID
#define SOME_UNIQUE_ID
// declarations , etc.
#endif
// end of file .h
There is nothing that prevents use of different suffixes, it's matter of how build process is organized. There is common agreement to name C files .c, C++ - .cpp, standard C++ headers wouldn't have suffix at all, while all other headers may have .h or .hpp. Include files that contain only inline functions sometimes are given .inc or .inl suffix instead of .h, but this isn't regulated in any way as far as I know
You can have only one definition per same scope with same ID. More of even while you may have several file scopes, for each .cpp a non-static declaration would generate duplicate IDs that would cause link-time error. You really should avoid using .cpp as include file, because in most build environments compiler would attempt to link it multiple times - for each use in #include and as separate module as well.
In your case you should put declarations of your arrays into .h file in form like this:
// fares.h
#ifndef FARES_H_
#define FARES_H_ // this will not allow declaration to be repeated
extern int gYourGlobalArray[100];
#endif
Word extern will tell the compiler that the symbol is defined elsewhere and would be found on link stage, the object should be static or thread storage duration, which in our case true as we declare global variable, and gets external linkage. Fares.cpp will have "implementation" that must contain symbols that will not be repeated.
// Fares.cpp
#include "fares.h" // necessary only if you require something declared there
// keep in mind that some file systems are case sensitive, some aren't and
// will not distinguish between Fares.h and fares.h
int gYourGlobalArray[100] = {};
That's actually defines thread duration storage for your array in file scope and allows it to be linked externally. Across entire project its identification should be unique (C++ compiler mangles names of some objects, e.g. functions, but in general you should avoid reusing IDs). If for some wild reasons ID in file scope repeats in different files but should not be linked externally, such storage should be declared static, that would disallow external linkage.
Declaring a static member of class usually either require similar definition in .cpp file (without keyword static) or requires initialization within class body, provided compiler supports that.
Next you only should add fares.cpp to your project\makefile\whatever you are using as compiling environment. fares.h goes into #include statements into .cpp or .h files that require it. #include statement technically just adds text of mentioned file to file wrote it in, exactly in that position.
(My apology if this question sounds familiar, but I was really confused. And I could not comment under existing questions. )
I browsed a few questions, this, whose answer says:
If ...(defined a function in header), and then include the header into two or more different source files, you'll have multiple definitions of the same function.
But I thought the book taught us to always wrote definition guard inside headers. With the guard, we won't have multiple definitions, right?
I tried to find the reason in book , but with not much help: it says the reason (why function is declared in header file, and defined in source file) is the same reason as variables (in a previous chapter). And when I jump to that previous chapter, there is no explicit explanation.
why declare a function in header but define it in source file?
The declaration is needed to call the function. It goes in the header so that any file which wants to call the function can include the header and have the declaration available.
There can only be one definition, so it goes in just one source file.
With the guard, we won't have multiple definitions, right?
There would be one definition in each source file that included the header. The guard prevents multiple inclusions from the same source file, but not inclusions from different source files.
But I thought the book taught us to always wrote definition guard inside headers.
Definition guard prevents a header to be included multiple times in one C file. It does not prevent a header from being included in multiple C files.
With the guard, we won't have multiple definitions, right?
If you put the definition in a header, and include that header in multiple C files, then you would end up with multiple definitions of the same function.
Having multiple definitions of a function or a variable will cause an error at linkage time, unless the function or the variable is static. In case of a static function / variable you would end up with multiple copies of that function / variable, which is not usually the desired outcome.
With the guard, we won't have multiple definitions, right?
Not right. Include guards ensure that when a source file is compiled, the header won't be processed twice. But when you have several source files, each file is compiled separately, so include guards do not stop multiple definitions.
That's not the same thing, using a definition guard doesn't prevent one implementation from spanning multiple source files, it prevents the same declaration from being included more than once in the same file (which would cause compilation errors indeed).
So a guard is useless against a function defined directly in the header, since its implementation will be then included in multiple source files and, unless the compiler chooses to inline it, it will be present more than once. Placing the implementation in the source file will make the function being compiled in its own translation unit, and any call to it will be resolved accordingly.
Actually the compiler could inline even functions implemented in the source file so this could not happen.
A declaration goes in the header.
A definition goes in the body.
The header guard is to prevent multiple declarations at compile time, while compiling a single unit that may include the same header more than once (via other The definition goes in the body to prevent multiple compiled versions of the definition in multiple objects that included it colliding at link time.
Edit to answer comment because I can't format a comment:
It's not OK to define the same thing twice.
It is not OK to declare the same thing twice.
It is OK to pre-declare the same thing twice.
// predeclare:
class thingy;
// declare:
class thingy { int x(); };
// define:
thingy::x() { return 1; }
Anything you put in a header is likely to appear twice when compiling a single file because headers often get included by other headers, so they get included more than once. Header guards prevent this at compile time.
Anything you put in a header which defines something is likely to end up being defined in the compilation of more than one file if they both include the header, and then appear twice at link time. Header guards cannot prevent this, hence we avoid defining things in headers.
You can think of the #include in C++ as a giant macro - it means "grab an entire file and shove it into my source code at this point, before you compile it".
I have a big project (400 files) and all of the headers have include guards and everything, however I get 500 LNK2005 errors.
Could it be that I have function bodies defined in some headers? Cause I saw the same things in the DirectX utility headers(DirectXCollision has some of it's functions are completely in the header).
Or could it be because they are using .inl files instead of .cpp?
Could it be that I have function bodies defined in some headers?
Yes, that could be. Defining a function in more than one translation unit results in a duplicated symbol definition error.
You can get around the duplication error by declaring those functions inline. [7.1.2]/2 reads:
A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.
Include guards will only save you from including the same header multiple times into the same compilation unit (one cpp file). If you include the header into a second cpp file and then link them together, both of them will have anything the header brings in. That's why it is usually a bad idea to have function implementations in the headers.
You can work around that by declaring your function inline, then compiler will copy/paste them around.
Do you define global variables in your header files? That can be a cause of the error.
And include guards will not help.
A global variable should be defined only in one translation unit and should be externed in all other translational unit.
For eg.
in x.h, you have
int myVar;
Now you #include x.h in both a.cpp & b.cpp,
then you will get a linker error even if you had include guards in x.h
Because now myVar will get defined in both a.obj and b.obj and the linker will find 2 myVars.
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).
Basically, my program was structured as follows:
The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).
Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc). CalledByCurrent.h contains a class definition.
There was a non-class function defined in CalledByCurrent.cc called thisFunction(). thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function). In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc. However, when I did this, I got an error saying that the function was duplicated. Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?
Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc. However, when I did this, I found that Current.cc did not know what function I was talking about. What the heck? I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem. Could you help me understand this behavior? Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?
p.s - I apologize for how confusing this post is. Please let me know if there's anything I can clear up.
You are getting multiple definitions from the linker - it sees two functions with the same name and complains. For example:
// a.cpp
void f() {}
// b.cpp
void f() {}
then
g++ a.cpp b.cpp
gives:
C:\Users\neilb\Temp\ccZU9pkv.o:b.cpp:(.text+0x0): multiple definition of `f()'
The way round this is to either put the definition in only one .cpp file, or to declare one or both of the functions as static:
// b.cpp
static void f() {}
You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.
EDIT
You can use the function in the other .cpp file by using extern keyword. See this example:
//Test.cpp
void myfunc()
{
}
//Main.cpp
extern void myfunc();
int main()
{
myfunc();
}
It will call myfunc() defined in test.cpp.
The header file inclusion mechanism should be tolerant to duplicate header file inclusions.
That's because whenever you simply declare a function it's considered in extern (global) scope (whether you declare it in a header file or not). Linker will have multiple implementation for the same function signature.
If those functions are truely helper functions then, declare them as;
static void thisFunction();
Other way, if you are using the same function as helper then, simply declare it in a common header file, say:
//CalledByCurrent.h (is included in both .cc files)
void thisFunction();
And implement thisFunction() in either of the .cc files. This should solve the problem properly.
Here are some ideas:
You didn't put a header include guard in your header file. If it's being included twice, you might get this sort of error.
The function's prototype (at the top) doesn't match its signature 100%.
You put the body of the function in the header file.
You have two functions of the same signature in two different source files, but they aren't marked static.
If you are using gcc (you didn't say what compiler you're using), you can use the -E switch to view the preprocessor output. This includes expanding all #defines and including all #includes.
Each time something is expanded, it tells you what file and line it was in. Using this you can see where thisFunction() is defined.
There are 2 distinct errors coming from 2 different phases of the build.
In the first case where you have a duplicate, the COMPILER is happy, but the LINKER is complaining because when it picks up all the function definitions across the different source files it notices 2 are named the same. As the other answers state, you can use the static keyword or use a common definition.
In the second case where you see your function not declared in this scope, its because the COMPILER is complaining because each file needs to know about what functions it can use.
Compiling happens before Linking, so the COMPILER cannot know ahead of time whether or not the LINKER will find a matching function, thats why you use declarations to notify the COMPILER that a definition will be found by the LINKER later on.
As you can see, your 2 errors are not contradictory, they are the result of 2 separate processes in the build that have a particular order.
I have C++ project which consists of multiple (in fact many) .cpp and .h files. While writing header files i have a file as follows
For eg MyHeaderFile.h
#ifndef _MYHEARDERFILE_H
#define _MYHEARDERFILE_H
// Here i have function defintion.
void myFunc() {cout << "my function" << endl; }
#endif
Above file is included in multiple files. While compiling i have getting "multiple definition of "myfunc" error.
I am expecting the header is included only once as i have #ifndef check so i am expecting error should not be thrown.
For example in case of templates we have to define in header file, in this case how we can avoid the problem i am facing now?
Can any one please help me why i am seeing the error? is my understanding right?
Thanks!
Normally, one puts function declarations in header files, and function definitions (i.e. the actual function body/implementation) in source files. Otherwise, you get exactly the issue you're seeing: the header file is #included (i.e. substituted) into multiple source files, so the function ends up being defined multiple times. This confuses the linker, so it complains.
The header-guard #ifndef ... stuff only prevents a header from being substituted into the same source file multiple times. Remember that each source file is compiled completely independently from all the others; all #defines and other definitions are "reset" for each one.
One possible alternative solution is to leave the function definition in the header file, but simply to mark it inline (this has the side-effect of eliminating the linker error). But, personally, I wouldn't do that.
Every function must be defined only once in a single translation unit (this is called One definition rule, and applies not only to functions). By placing the definition in a header which is then included, you are violating this rule.
You can simply leave the declaration
void myFunc();
in the header, and define myFunc in a .cpp which provides the definition.
Otherwise you can declare your function inline.
Note that when using templates, instead, you are usually led (for template-related specific issues) to place definitions directly in the headers, which could appear surprising given the problems you are facing now.