C++ Multiple defintions error - c++

I don't wish to create a wall of code so if you need any code just ask and i will post. I am getting multiple definition errors and i have no idea why. i believe the error is occurring because i am attempting to declare a variable in one header file(as well as create an object for it in the same header) and then use it among 4 different files.and for each file i use the header in i get multiple definition, with the small amount of info i have given you any ideas as to why this is occurring?
please ask if more information is required to solve the question.
I am using Code::Blocks ide mingW compiler and programming on Windows 7
EDIT
Thanks you all for your extremely fast help you have solved my problem :D

Don't declare it in a header file (although technically, I mean don't define it there).
In your header file you should have:
extern int variableIWantOneCopyOfOnly;
and then, in a single C source file that you will link in, put:
int variableIWantOneCopyOfOnly;
The former will let all your source files know about the existence of the variable but without allocating space for it. The single translation unit containing the second line will allocate the space for it and the linker will fix up all the references to it.
Include guards won't help with multiple definitions since they only stop the inclusion within a single translation unit.
By that I mean, if you have the following files:
xyz.h: xyz1.c: xyz2.c:
#ifnef XYZ #include "xyz.h" #include "xyz.h"
#define XYZ
int a;
#endif
and you execute a command like:
gcc xyz1.c xyz2.c
then they will both get the own copy of a, not share a copy, because the scope of the include guard is the translation unit, not the executable created by the linker.

Have you used include guards in your header? Generally, you want to structure your headers something like this:
#ifndef _HEADER_FILE_H
#define _HEADER_FILE_H
// actual definitions
#endif
There's also #pragma once, but that is not standard.

"as well as create an object for it in the same header"
If you define things in your headers, and then try to link objects from multiple translation units including that header, you'll get multiple definition errors.
If the header's called say x.h, create an x.cc (or x.c++, x.cpp or whatever you normally do) that includes the header. Move the definition of the object in there. Compile it and link it with the other objects in your application.

the multiple definition error means you are declaring many times the same variable. Regarding what you are doing, this occurs because you are including 4 times the same file (so you are declaring 4 times your variables.
Add the preprocessor
#ifndef _HEADERFILE_H
#define _HEADERFILE_H
// Your declarations
#endif
or if you are using Visual studio just add this on the first line of the file:
#pragma once

You should move the actual definition into a c++ (.cc .cpp whatever) file and only leave the declaration within the header. Also you will need to prefix the declaration with 'extern'.

Related

Need clarification on #ifndef #define

The code I am working has multiple headers and source files for different classes face.cc, face.hh, cell.cc, cell.hh edge.cc edge.hh and the headers contain includes like this,
#ifndef cellINCLUDED
#define cellINCLUDED
#ifndef faceINCLUDED
#define faceINCLUDED
I saw through http://www.cplusplus.com/forum/articles/10627/ and saw the way to write include guard is
#ifndef __MYCLASS_H_INCLUDED__
#define __MYCLASS_H_INCLUDED__
So in above code that I am working on, does compiler automatically understands it is looking for face.hh or cell.hh files?
better question : Is writing __CELL_H_INCLUDED__ same as cellINCLUDED ?
#ifndef __MYCLASS_H_INCLUDED__
#define __MYCLASS_H_INCLUDED__
So in above code that I am working on, does compiler automatically
understands it is looking for face.hh or cell.hh files?
No, the compiler doesn't automatically understand what you mean.
What really happens is that, when compiling a translation unit, the Compiler holds a list of globally defined MACROs. And so, what you are doing is defining the MACRO __MYCLASS_H_INCLUDED__ if it doesn't already exists.
If that macro is defined, that #ifndef until #endif will not be parsed by the actual compiler.
Hence you can test for the existence of that MACRO to determine if the Compiler has parsed that header file to include it once and only once in the translation unit... This is because the compiler compiles each translation unit as one flattened file (after merging all the #includes)
See https://en.wikipedia.org/wiki/Include_guard
Is writing __CELL_H_INCLUDED__ same as cellINCLUDED ?
Yes it is.... The reason some prefer using underscored prefixed and suffixed MACROs for include guards is because they have extremely low probability of ever being used as identifiers... but again, underscore could clash with the compiler...
I prefer something like this: CELL_H_INCLUDED
If you use cellINCLUDED, there are chances that someday, somebody may use it as an identifier in that translation unit
The preprocessor definitions have no special meaning. The only requirement is that they stay unique across the modules, and that's why the file name is typically a part of them.
In particular, the mechanics for preventing double inclusion aren't "baked in" the language and simply use the mechanics of the preprocessor.
That being said, every compiler worth attention nowadays supports #pragma once, and you could probably settle on that.
As the link you have referenced says, "compilers do not have brains of their own" - so to answer your question, no, the compile does not understand which particular files are involved. It would not even understand that '__cellINCLUDED' has anything conceptually to do with a specific file.
Instead, the include guard simply prevents the logic contained between its opening #ifndef and closing #endif from being included multiple times. You, as the programmer, are telling the compiler not to include that code multiple times - the compiler is not doing anything 'intelligent' on its own.
Nope, This is essentially telling the compiler/parser that if this has already been put into the program, don't puthave already been loaded.
This should be at the top (and have an #endif at the bottom) of your .h file.
Lets say you have mainProgram.cpp and Tools.cpp, with each of these files loading fileReader.h.
As the compiler compiles each cpp file it will attempt to load the fileReader.h. unless you tell it not to it will load all of the fileReader file in twice.
ifndef = if not defined
so when you use these (and the #endif AFTER all your code in the .h file)
you are saying:
if not defined: cellINCLUDED
then define: cellINCLUDED with the following code:
[code]
end of code
so this way when it goes to load the code in your .h file a second time it hits the if not defined bit and ignores the code on the second time.
This reduces compile time and also means if you are using a poor/old compiler it isn't trying to shove the code in again.

C++ class redefinition error - Help me understand headers and linking

I started writing a simple interpreter in C++ with a class structure that I will describe below, but I quit and rewrote the thing in Java because headers were giving me a hard time. Here's the basic structure that is apparently not allowed in C++:
main.cpp contains the main function and includes a header for a class we can call printer.h (whose single void method is implemented in printer.cpp). Now imagine two other classes which are identical. Both want to call Printer::write_something();, so I included printer.h in each. So here's my first question: Why can I #include <iostream> a million times, even one after the other, but I can only include my header once? (Well, I think I could probably do the same thing with mine, as long as it's in the same file. But I may be wrong.) I understand the difference between a declaration and an implementation/definition, but that code gives me a class redefinition error. I don't see why. And here's the thing that blows my mind (and probably shows you why I don't understand any of this): I can't just include printer.h at the top of main.cpp and use the class from my other two classes. I know I can include printer.h in one of the two classes (headers) with no trouble, but I don't see why this is any different than just including it before I include the class in main.cpp (as doing so gives me a class not found error).
When I got fed up, I thought about moving to C since the OOP I was using was quite forced anyway, but I would run into the same problem unless I wrote everything in one file. It's frustrating to know C++ but be unable to use it correctly because of compilation issues.
I would really appreciate it if you could clear this up for me. Thanks!
Why can I #include a million times, even one after the other, but I can only include my header once?
It is probably because your header doesn't have an include guard.
// printer.h file
#ifndef PRINTER_H_
#define PRINTER_H_
// printer.h code goes here
#endif
Note that it is best practice to chose longer names for the include guard defines, to minimise the chance that two different headers might have the same one.
Most header files should be wrapped in an include guard:
#ifndef MY_UNIQUE_INCLUDE_NAME_H
#define MY_UNIQUE_INCLUDE_NAME_H
// All content here.
#endif
This way, the compiler will only see the header's contents once per translation unit.
C/C++ compilation is divided in compilation/translation units to generate object files. (.o, .obj)
see here the definition of translation unit
An #include directive in a C/C++ file results in the direct equivalent of a simple recursive copy-paste in the same file. You can try it as an experiment.
So if the same translation unit includes the same header twice the compiler sees that some entities are being defined multiple times, as it would happen if you write them in the same file. The error output would be exactly the same.
There is no built-in protection in the language that prevents you to do multiple inclusions, so you have to resort to write the include guard or specific #pragma boilerplate for each C/C++ header.

Clarification about the header-guards and header-file inclusion used in C/C++

I know people recommend including header guards in header files, to prevent header files contents from being inserted by the pre-processor into the source-code files more than once.
But consider the following scenario:
Let's say I have the files main.cpp , stuff.cpp, and commonheader.h, with the .h file having its header guards.
If either .cpp files tries to include commonheader.h more than once, then the preprocessor
will stop that from happening, and after compiling to object code we get,
main.o containing the contents of commonheader.h exactly once.
stuff.o containing the contents of commonheader.h exactly once.
Note that the contents of commonheader, have been repeated across the files, but not within the same .o file.
So what happens during the linking step? Since the .o files are being fused into an exectuable
we will have to ensure for a second time that the contents of commonheader are not being repeated. Does the compiler take care of that? If not, wouldn't that be a problem when we are dealing with huge header files, giving rise to code repetition across files and leading to large executable sizes.
If I am making some conceptual mistake anywhere in the question, please correct me.
Typically your header file should not actually define any symbols, it should just declare them. So commonheader.h would look like this (omitting the include guards):
void commonFunc1(void);
void commonFunc2(void);
In that case, there is no problem. If you call commonFunc1 in main.cpp and stuff.cpp, both main.o and stuff.o will know they want to link against a symbol called commonFunc1 and the linker will try to find that symbol. If the linker doesn't find the symbol, you get an undefined reference error. The actual definition of commonFunc1 needs to be in some cpp file.
If you really want to define functions in your header file, use static so that the linker does not see them. So your commonheader.h could look like:
static void commonFunc1()
{
/* ... do stuff ... */
}
In this case, the linker does not know about commonFunc1 and no errors will occur. This could increase the executable size though; you'll probably end up with two copies of the code for commonFunc1.
To expand Grayson's answer to cover variables. If you want to declare a variable in a header file you should use the extern keyword. This is one way to handle global variables.
In the header file global.h you write this:
extern Globals globals;
then you can use foo in any file including global.h, while in global.cpp you write
#include "globalstype.h"
Globals globals;
Note that global.cpp doesn't need to include global.h, however you will need to make sure global.cpp is compiled into each usage otherwise the linker will complain.
Header files normally contain declarative code not definitive code. That is they declare the existence of something that must exist exactly once. Macros and inline functions are allowed and necessarily duplicate wherever they are used.
The declarations are used by the compiler to insert unresolved links (or references) into the object code. The job of the linker is to resolve these links by matching the reference with the one single definition.
If you omit the include guards, with multiple inclusion in a single translation unit you will get a compiler error for multiple declaration of an existing symbol. If however you have a header erroneously containing a definition, and the header is included in more than one translation unit, there will be more than one object file with a definition - this instead causes a linker error for multiple definition.
So while:
extern int b ; // declaration, may occur in multiple translation units
is fin in a header file,
int b ; // definition, must occur in only object file.
is not.
Not the the declarations are not included in the object code, rather the compiler uses them to create references that the linker will resolve if the compiler has not already uses the definition and resolved it already.
Yes, it can be a problem. You could end up with multiple definitions, or redundant copies.
C is quite simple in this regard. You have static, extern, and inline -- and compilers also define several ways to alter visibility. I think a lot of this has been covered by other answers.
C++ is quite different, however. There is a lot of information and there are also implicit definitions (e.g. the compiler may emit a copy constructor or RTTI).
With C++, the likelihood that a definition appears in a header is much more likely -- consider templates, methods defined in a class declaration, and so on. C++ defaults to using the One Definition Rule. You will want to read about it in more detail, but it basically states that some categories of symbols may be multiply-defined; depending on the decoration and the location/scope of declaration, that in many cases, the linker is allowed to assume that each body (definition) is identical and it is free to discard any copies it encounters (leaving one definition in your binary). So this really cuts down on the size of the resulting binary, unless you specify a copy shall be produced.
However, having those definitions in your headers can surely increase compilation times, memory and files required to compile each file, visible dependencies, and will increase the number of files which must be recompiled when a definition is edited.
Of course, the language still allows bad forms, and will not complain if you repeatedly state over and over again and include in multiple translations definitions which must be copied for each translation. Then you can certainly end up with a lot of bloat.
This may be a good intro:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=386

function defintion in header file in C++

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.

Preprocessor directive #ifndef for C/C++ code

In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...