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.
Related
I'm working my way through a C++ tutorial, and in one of the articles on the preprocessor/header files the author creates 2 'header files' (not the technical term, of course), example.h and example.cpp. In example.h he puts the forward declarations for the functions and the header guard, and in example.cpp the actual body of the functions. Why is this? I tried putting the body of the function in the example.h file and it worked just fine, so why does he put it separately? Is it customary, or does it pose problems in bigger problems? Or what?
Can someone please enlighten me on this...
C++ has a rule called the one-definition rule that says that every function needs to be defined once and only once (there are a few exceptions to this rule, but we'll ignore them for now.) The function prototype typically included in a header file is a declaration saying that the function exists, and the implementation in the .cpp file is the definition giving the code for the function.
If you put the definition of the function in a header file and then include the header file in multiple places, you'll get linker errors because you're breaking the one definition rule - each .cpp file that's compiled will have its own copy of the definition of the function. On the other hand, if you just put the declaration in the header and then put the definition in a single source file, then there's only one definition and nothing will break.
There are a few exceptions for the one definition rule. First, all inline functions are exempt from ODR, so you could potentially put function definitions in a header file if you mark all the functions inline, though this is generally not considered a good idea for all but the smallest functions. Second, template functions are exempt from the ODR, which (among other things) is one of the reasons you see template functions defined in headers.
Put the function body in example.h. Then, when you write a second .cpp file that also includes example.h, and link it with example.cpp, then you'll get a linker error. The linker will see 2 definitions of the function in example.h.
Becouse in the header file you only declare functions that is really important when you want to use a custom linking configuration. For example if a function is defined in a file object and is used in an another object the linker must have the same reference for this function to link the two different files.
(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 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()
{
}
I have a very simple class and I'd like to consolidate it to a single .h file. Will everything work the same if I cut and paste the guts of my .cpp to the bottom of my .h?
In particular, there are static member variable initializations int MyClass::myStaticVar = 0; outside of any class definition at the top of the .cpp, and following that, there are static member function implementations void MyClass::myStaticMethod() {...}. Some non-static member functions are already being implemented in the .h, not the .cpp. So you can see there are some nuances here that I'd like to clarify.
Edit So far, what I'm getting is:
This is naughty, but it will work if you only #include the .h once.
It breaks the convention and doesn't really work like a .h so it might
as well be named .doofus.
Now, for example, look at the TUIO C++ bindings. A lot of the classes consist of one .h file, no cpp (TuioPoint.h, TuioCursor.h, TuioObject.h, etc). I don't think this is so bad...
If you're left with a single cpp file in the entire project, then it will work (but it's bad practice). If you have two cpp files that both include that header, you're breaking the one definition rule, and you (should) get linker errors.
You can do this if (A) All the functions are templates (in fact, you must in this case), or (B) all the functions are marked as inline.
[Edit]
The reason you aren't already having problems is a function defined in the class definition is automatically marked as inline. Thus: no problems. However, if the function is defined outside of the class definition, it should be in a cpp file. Also, static members should always be in a cpp file.
[Edit2] The reason non-inline, non-template functions and File scope varaibles (globals and static members) should always be in a cpp file, is that when the compiler finds that line of code, it creates the function/variable right there. Obviously, it must be created once to be used. Why not in a header file? Because then if the header is included in two cpp files, it will be created in two places (I have hpp files at work that are literally included in several thousand cpp files). C++ has a "one-definition rule" where each function/object can only be defined/created once, to prevent this obvious error:
int MyClass::myStaticVar = 0;
int MyClass::myStaticVar = 7;
Which would it use? You've just created two variables with the same name! So this isn't allowed, even if they were exactly the same, (except for inline/template). Each cpp file is compiled once and only once (unless for some oddball reason it's included from something else), which prevents accidental violations of the one-definition rule.
Also, hpp files are for declarations, and cpp files are for definitions/instantiations.
what good would the .h file be anymore? you can't have multiple .cpp files #include this .h file. And if this .h is only included by a single .cpp, then why do you need the .h file in the first place - just put everything in the .cpp.
In addition to Mooings answer you might want to consider the compile/link process for a while.
The compiler compiles the .cpp files, not the .h files (by convention).
This has the consequence that for each .cpp file you need the definitions for the classes you reference in order to create instructions for the code in the .cpp. The .h files provides that.
What you do not want is identical pieces of code being duplicated across your program, which would be the consequence of compiling .cpp files including headers with implementations(what you are suggesting); hence the one definition rule.
In a one .cpp-file project as Mooing suggests you can of course abuse this to your delight as long as you have a .cpp with a main and only one set of includes.
Essentially, this is what #include does (it pastes the header into the cpp, basically doing the same thing in a sense). So, yes, everything SHOULD work out fine, assuming no odd cases. I can't see why you would want to do this though. You'd be better off just flat out defining the functions and such in the class definition or just using #include. Is there any reason you're choosing not to?
EDIT: In response to your edits, why are you implementing members in the header? I'd suggest moving those to the .cpp unless this is a template class or some similar special case. Use the header for prototype and decleration, use the cpp for definition. That should solve any issues for you.
I am working on porting some source code to a linux system, and as expected, some stuff is broken. One thing that is throwing an error for me right now, is that someone has a .h and a .cpp file that both use fclose()
The compiler is complaining about fclose() being undeclared in the header file.
here was the function declaration in the header file:
void closeFile() { if (fp) fclose(fp); }
Now, I think this is bad style, but also - how did they get this working before? Did their version of the compiler allow this kind of behavior?
Should I fix this by including stdio in the header, or move the whole thing to the cpp?
It's not bad style, you can put source code in header files, and some times you're forced to, in particular:
When defining a template class/function.
When defining an inline function.
Anyway you shouldn't put a free (defined outside a class scope) non-inline function in a header file, since that would be compiled any time a source file include such header (and this will give you a linking error).
If you're getting an error that states fclose hasn't been declared, it's probably because cstdio (or stdio.h) wasn't declared before that piece of code. Put an #include <cstdio> at the beginning of the header file.
Just to add 2 things about the other answers, remember inline is not an order, is more a guess of what the compiler should do, unless you force inline. Most compilers can decide when to inline a function, even if you did not declare it inline. It's not a must, it is a should.
Sometimes you really need to include such function/structs/classes definitions in the header, and sometimes they are not trivial or that simple. But those definitions are usually some auxiliar functions you need and you just don't want to include them on the main file, just to organize things better.
The best examples I ever seen (ok, and I didn't see those many) about this practice is game source code (that's my main interest :) ).
By the way, I usually do not put any declaration on header files (except structs and enums), I put them on separated files, unless if:
There are only a few declarations/aux functions to be made; or
These declarations are functions that I will use in another contex (of the same project, in the case) and I just think it's better to treat them as a separated 'auxiliar library' (within the same context).
Hope it helps somewhat.
Keep in mind that header files aren't compiled by themselves (usually). They are #included into source files and the definitions available when the header file is parsed are whatever was included in the source file above the header file in question.
Regardless of whether the header file is an appropriate place for the implementation of closeFile(), your header file should #include everything it needs at the top of itself. So, add #include <stdio.h> at the top of the header file.
(Note that if this is code intended to be compiled into the Linux kernel itself, you may need a different header than stdio.h. Often application-level headers aren't suitable to be used in the kernel sources.)
fclose() will be undefined if you haven't included stdio.h either in this header or before it everywhere this header is used. That is why the error occurs.
I personally see nothing wrong with the code being allowed to be in a header file, however, if it is, and you're using C99, you should declare it
inline void closeFile() { if (fp) fclose(fp); }
This means multiple compiled objects won't have closeFile() symbols (because of inline) and the inline hints to the compiler that this shouldn't be left as a function call but substituted inline which is probably want you want for speed.
The headers are included by textual substitutions (that is the whole content of the header is substituted to the #include declaration). So if there is only one .cpp file that include this particular header, this is equivalent with having the function defined in the .cpp file. I think this is the reason why it was working (at link time).
The C standard only define the header that must be included to have a function available but does not forbid the system header to include one another. So it is possible that on some system, the stdio.h header was implicitly included by another header (and thus no error reported by the compiler).
Personally, I would move such code to the .cpp file, as it will be less brittle (the header can be included by multiple .cpp files, the header will not require a previous inclusion of the stdio.h header) and will allow for quicker recompilation if the implementation must be changed (to add logging or proper error handling, as closing a file can fail).