Just spent a while debugging a multiple definition error but I'm unclear on why this behavior occurred and would like to understand.
I had something similar to this in a header file.
//foo.h
#pragma once
my_states States[N] = {...};
Later, bar.h includes foo.h as bar.cpp has functions which need to know about my_states.
The issue arose when I was writing unit tests for bar and included bar.h in test.cpp.
bar.o: multiple definition of MyNamespace::named_states
test.o: first defined here
I have fixed the issue by changing to
constexpr my_states States[n] = {...}; in foo.h.
However I do not understand why this fixed the issue. I understand I had multiple definitions for the symbol my_states which confused the linker, but if I have my #pragma once guard in place, why was this being defined multiple times? I'm unsure why I need the constexpr qualifier to denote that this should only have 1 definition, when as far as I understand #pragma once should have prevented the compiler from attempting to create more than 1 definition in the first place.
#pragma once only ensures that header files are included once only, it doesn't deal with the code.
On your second question regarding my_states - without constexpr you attempt to define a global variable that can be modified in runtime (or something like that). By settings its state in the header, you defacto make each library that includes this header file instantiate and contain the variable while it is supposed to be uniquely defined... basically it's a complete mess that cannot compile. You can declare static/global variables in header files but you ought to instantiate them in a single cpp file.
By adding constexpr to the variable declaration you convey to compiler that it cannot be modified in runtime, and moreover, it's value is known at compile time. So there is no worry about which library stores / instantiates it or anything of the sort since it is an absolute constant known at compile time.
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.
I have what seems a relatively simple question, but one that keeps defying my efforts to understand it.
I apologise if it is a simple question, but like many simple questions, I can't seem to find a solid explanation anywhere.
With the below code:
/*foo.c*/
#include "bar.h"
int main() {
return(my_function(1,2));
}
/*bar.h*/
int my_function(int,int);
/*bar.c*/
#include "bar.h" /*is this necessary!?*/
int my_function(int x, int y) {
return(x+y);
}
Simply, is the second inclusion necessary? I don't understand why I keep seeing headers included in both source files. Surely if the function is declared in "foo.c" by including "bar.h," it does not need to be declared a second time in another linked source file (especially the one which actually defines it)??? A friend tried to explain to me that it didn't really matter for functions, but it did for structs, something which still eludes me! Help!
Is it simply for clarity, so that programmers can see which functions are being used externally?
I just don't get it!
Thanks!
In this particular case, it's unnecessary for the reason you described. It might be useful in situations where you have a more complex set of functions that might all depend on each other. If you include the header at the top of the .cpp file, you have effectively forward-declared every single function and so you don't have to worry about making sure your function definitions are in a certain order.
I also find that it clearly shows that these function definitions correspond to those declarations. This makes it easier for the reader to find how translation units depend on each other. Of course, the names of the files might be sufficient, but some more complex projects do not have one-to-one relationship between .cpp files and .h files. Sometimes headers are broken up into multiple parts, or many implementation files will have their external functions declared in a single header (common for large modules).
Really, all inclusions are unnecessary. You can always, after all, just duplicate the declarations (or definitions, in the case of classes) across all of the files that require them. We use the preprocessor to simplify this task and reduce the amount of redundant code. It's easier to stick to a pattern of always including the corresponding header because it will always work, rather than have to check each file every time you edit them and determine if the inclusion is necessary or not.
The way the C language (and C++) is designed is that the compiler processes each .c file in isolation.
You typically launch your compiler (cl.exe or gcc, for example) for one of your c files, and this produces one object file (.o or .obj).
Once all your object files have been generated, you run the linker, passing it all the object files, and it will tie them together into an executable.
That's why every .c file needs to include the headers it depends on. When the compiler is processing it, it knows nothing about which other .c files you may have. All it knows is the contents of the .c file you point it to, as well as the headers it includes.
In your simplified example inclusion of "bar.h" in "bar.c" is not necessary. But in real world in most cases it would be. If you have a class declaration in "bar.h", and "bar.c" has functions of this class, the inclusion is needed. If you have any other declaration which is used in "bar.c" - being it a constant, enum, etc. - again include is needed. Because in real world it is nearly always needed, the easy rule is - include the header file in the corresponding source file always.
If the header only declares global functions, and the source file only implements them (without calling any of them) then it's not strictly necessary. But that's not usually the case; in a large program, you rarely want global functions.
If the header defines a class, then you'll need to include it in the source file in order to define member functions:
void Thing::function(int x) {
//^^^^^^^ needs class definition
}
If the header declares functions in a namespace, then it's a good idea to put the definitions outside the namespace:
void ns::function(int x) {
//^^^^ needs previous declaration
}
This will give a nice compile-time error if the parameter types don't match a previous declaration - for which you'd need to include the header. Defining the function inside its namespace
namespace ns {
void function(int x) {
// ...
}
}
will silently declare a new overload if you get the parameter types wrong.
Simple rule is this(Considering foo is a member function of some class):-
So, if some header file is declaring a function say:=
//foo.h
void foo (int x);
Compiler would need to see this declaration anywhere you have defined this function ( to make sure your definition is in line with declaration) and you are calling this function ( to make sure you have called the function with correct number and type of arguments).
That means you have to include foo.h everywhere you are making call to that function and where you are providing definition for that function.
Also if foo is a global function ( not inside any namespace ) then there is no need to include that foo.h in implementation file.
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
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'.
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.