Multiple definition error in Dev-C++ [duplicate] - c++

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.

Related

Understanding C linker error: multiple definition

I have a project with multiple header files and .cpp files.
All of the header files have include guards.
There is a file called Constants.h where I define some constants. Some of these with defines, some as constant variables.
There are more header-.cpp-file pairs with code in them. One of these does contain a class, the others don't.
When I include my files into my main file (an arduino sketch), I get a lot of linker errors, claiming there are multiple definitions of some variables.
I read that this mainly occurs when you include .c or .cpp files, which I don't do. All the .cpp files only include their appropriate header files.
I did manage to find multiple solution proposals:
1) inline:
With functions, inline can be used to get rid of this problem. However, this is not possible with variables.
2) anonymous namespace:
This is one of the solutions I used. I put anonymous namespaces around all the problematic definitions I had. It did work, however I do not understand why this works. Could anyone help me understand it?
3) moving definitions into .cpp files:
This is another approach I used sometimes, but it wasn't always possible since I needed some of my definitions in other code, not belonging to this header file or its code (which I do admit is bad design).
Could anyone explain to me where exactly the problem lies and why these approaches work?
Some of these with defines, some as constant variables.
In C const does not imply the same thing as it does in C++. If you have this:
const int foo = 3;
In a header, then any C++ translation unit that includes the header will have a static variable named foo (the const at namespace scope implies internal linkage). Moreover, foo can even be considered a constant expression by many C++ constructs.
Such is not the case in C. There foo is an object at file scope with external linkage. So you will have multiple definitions from C translation units.
A quick fix would be to alter the definitions into something like this:
static const int foo = 3;
This is redundant in C++ but required in C.
In addition to Story Teller's excellent explanation, to define global variables, use the following:
// module.h
#include "glo.h"
// glo.h
#ifndef EXTERN
# define EXTERN extern
#endif
EXTERN int myvar;
// main.c
#define EXTERN
#include "glo.h"
In main.c all variables will be declared (i.e. space is allocated for them), in all other c files that include glo.h, all variables will be known.
You shouldn't declare any object in header files, this should be moved to c\c++ files.
In header you may:
declare types such as: classes, structs, typedefs etc.
put forward declarations of (not classes) functions
put inline (or in classes) functions (+ body)
you may add extern declaration.
you may put your macros.
a static declaration may declare things multiple times, therefore it is not recommended.

What is the difference between including a .c file and a .h file

Lot of the times when I watch other people's code I see some are including a .h file and some are including a .c/.cpp file. What is the difference?
It depends on what is in the file(s).
The #include preprocessor directive simply inserts the referenced file at that point in the original file.
So what the actual compiler stage (which runs after the preprocessor) sees is the result of all that inserting.
Header files are generally designed and intended to be used via #include. Source files are not, but it sometimes makes sense. For instance when you have a C file containing just a definition and an initializer:
const uint8_t image[] = { 128, 128, 0, 0, 0, 0, ... lots more ... };
Then it makes sense to make this available to some piece of code by using #include. It's a C file since it actually defines (not just declares) a variable. Perhaps it's kept in its own file since the image is converted into C source from some other (image) format used for editing.
.h files are called header files, they should not contain any code (unless it happens to contain information about a C++ templated object). They typically contain function prototypes, typedefs, #define statements that are used by the source files that include them. .c files are the source files. They typically contain the source code implementation of the functions that were prototyped in the appropriate header file.
Source- http://cboard.cprogramming.com/c-programming/60805-difference-between-h-c-files.html
you can look at gcc website (https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html) that reports a good summary of all the extensions that you can use in C/C++:
C++ source files conventionally use one of the suffixes ‘.C’, ‘.cc’, ‘.cpp’, ‘.CPP’, ‘.c++’, ‘.cp’, or ‘.cxx’; C++ header files often use ‘.hh’, ‘.hpp’, ‘.H’, or (for shared template code) ‘.tcc’; and preprocessed C++ files use the suffix ‘.ii’. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).
Including header file with declarations is the main, recommended and used almost anywhere, method for making consistent declarations among a project. Including another source file is another (very rare) kind of beast, and it's useful and possible under specific conditions:
There is a reason to split code to separate source files despite it shall be compiled as a single module. For example, there are different versions of some functions which shan't be visible from another modules. So, they are declared static but which version is included is regulated by compile options. Another variant is size and/or maintanenance credentials issues.
The included file isn't compiled by itself as a project module. So, its exported definitions aren't in conflict with the module that file is included to.
Here, I used terms definition and declaration in the manner that the following are declarations:
extern int qq;
void f(int);
#define MYDATATYPE double
and the following are definitions:
int qq; // here, the variable is allocated and exported
void f(int x) { printf("%d\n", x); } // the same for function
(Also, declarations include C++ methods with bodies declared inside their class definition.)
Anyway, the case another .c/.cxx/etc. file is included into source file are very confusing and shall be avoided until a very real need. Sometimes a specific suffix (e.g. .tpl) is used for such files, to avoid reader's confusion.

Adding more code makes code uncompileable

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()
{
}

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

Will everything work the same if I cut and paste my .cpp to the bottom of my .h?

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.