MyNamespace.h:
namespace MyNamespace{
int a
}
MyNamespace.cpp: some function that uses a
main.cpp
#include "MyNamespace.h"
main.obj : error LNK2005: "class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >
FileNamespace::m_rootDirectoryPath"
(?m_rootDirectoryPath#FileNamespace##3V?$basic_string#_WU?$char_traits#_W#std##V?$allocator#_W#2##std##A)
already defined in FileNamespace.obj
1>main.obj : error LNK2005: "struct FileNamespace::FileTree FileNamespace::m_dataFileTree"
(?m_dataFileTree#FileNamespace##3UFileTree#1#A) already defined in
FileNamespace.obj
You are defining a global variable (with external linkage) in multiple translation units, which results in duplicate definition errors (since you are violating the ODR).
What you should do, instead, is to declare it in the header with an extern declaration
namespace MyNamespace{
extern int a;
}
and define it in a single .cpp file (probably in MyNamespace.cpp)
int MyNamespace::a;
This way, the compiler will create only one instance of this variable in a single object module, and the linker will link all the references to it made in other object modules to this single instance.
It may help you to understand the problem noticing that this is the exact equivalent of declaring functions in headers (writing there only the prototype) and defining them in a single .cpp.
Namespaces are no different from other variables; in your header, you are actually defining the "a", not just declaring it.
In your header:
namespace MyNamespace{
extern int a;
}
In one source file:
int MyNamespace::a;
Related
I'm trying to make a namespace and its members available globally however I am running into already defined errors.
Settings.h
#pragma once
#include "boost/property_tree/json_parser.hpp"
#include <string>
using json = boost::property_tree::ptree;
namespace Settings {
extern std::string settingsPath;
extern json settings;
extern void init();
extern void readSettings();
extern void writeSettings();
};
Settings.cpp
#pragma once
#include "Settings.h"
using json = boost::property_tree::ptree;
namespace Settings {
void init() {
}
void readSettings() {
}
void writeSettings() {
}
};
I am forward declaring the Settings namespace and members and using extern. I have no idea what I'm doing wrong. Please could someone point out the error here.
Thanks
Edit: The actual error messages:
Error LNK2005 "class std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> > Settings::settingsPath" (?settingsPath#Settings##3V?$
basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##A) already defined in
AmalgamService.obj Amalgam F:\Dropbox\CPP\Visual Studio Projects\Amalgam\Amalgam\
main.obj 1
And repeat for all members of the namespace. The Settings.h is #includeed in main.cpp and AmalgamService.cpp
You seem to be including Settings.cpp in another file. Do not include .cpp files. This results in duplicate definitions. This also means that #pragma once in .cpp files is useless.
You need to keep in mind that #include is just a glorified copy&paste tool. When you #include a file, that file is literally being copy&pasted into the spot of the #include statement. So including a .cpp file means you will get multiple definitions of everything defined in that .cpp file.
Furthermore, you don't have to use extern when declaring functions. Functions are extern by default, unless you say otherwise.
Variables are extern by default too, however you need to use extern as a way to declare them without defining them:
extern int var; // declaration
int var; // definition
Functions don't need that, because you can declare them by omitting their body:
void func(); // declaration
void func() { } // definition
You are allowed to declare things multiple times, which is why you can #include header files (like .h, .hpp) in multiple files. But you are not allowed to define things multiple times, which is why you can't #include non-header source files.
I got the following declaration:
// file MadaPacket.h
class MadaPacket
{
// ....
public:
inline static bool word_is_header(int w);
}
And as the correspondent declaration:
// file MadaPacket.cpp
#include "MadaPacket.h"
inline bool MadaPacket::word_is_header(int w)
{
return w == 0xFBBA;
}
MSVC12 builder fails at linkage, with the following reason:
unresolved external symbol "public: static bool __cdecl MadaPacket::word_is_header(int)
Adding static to definition pushes error
'static' should not be used on member functions defined at file scope
Removing inline from definition pushes error
unresolved external symbol "public: static bool __cdecl MadaPacket::word_is_header(int)
I guess I'm misunderstanding some of the definition-declaration relationship.
EDIT
Obviously I'd like to have both the modifiers, if this is possible ofc.
Remove the inline keyword from both places.
The inline keyword should be used only when defining functions in header files that are included from multiple translation units. Well, there are other situations where it can be used too, but here none of them apply.
You don't have an identical list of modifiers for your definition in your .h file and your .cpp file. Both definitions should be exactly the same for the linker to find them. So I'd first remove 'static' from both and recompile.
I know this is a common problem, but I am pretty sure there is no error with how I include the files.
I'll give you the basic files.
Main.cpp:
#include "GameState.h"
#inlcude "Timer.h"
int main ( int argc, char** argv ) {
GameState.h:
#pragma once
#include "Character.h"
Character.h:
#pragma once
#include "Setup.h"
Setup.h:
#pragma once
#include "SDL.h"
#include "SDL_main.h"
#include "SDL_image.h"
Error report:
Error 1 error LNK2005: "void __cdecl apply_surface(int,int,struct SDL_Surface *,struct SDL_Surface *,struct SDL_Rect *)" (?apply_surface##YAXHHPAUSDL_Surface##0PAUSDL_Rect###Z) already defined in Character.obj C:\Users\Jim\Documents\C++\herorpg\herorpg\Main.obj
Error 2 error LNK2005: "bool __cdecl init(struct SDL_Surface * &)" (?init##YA_NAAPAUSDL_Surface###Z) already defined in Character.obj C:\Users\Jim\Documents\C++\herorpg\herorpg\Main.obj
Error 3 error LNK2005: "bool __cdecl load_files(struct SDL_Surface * * const)" (?load_files##YA_NQAPAUSDL_Surface###Z) already defined in Character.obj C:\Users\Jim\Documents\C++\herorpg\herorpg\Main.obj
Error 4 error LNK2005: "struct SDL_Surface * __cdecl load_image(char *)" (?load_image##YAPAUSDL_Surface##PAD#Z) already defined in Character.obj C:\Users\Jim\Documents\C++\herorpg\herorpg\Main.obj
Error 6 error LNK1169: one or more multiply defined symbols found C:\Users\Jim\Documents\C++\herorpg\Debug\herorpg.exe
Is there anything wrong with what I'm including? If you think more information is required, I'll post the full code. Just seemed like a nuisance before.
C++ has a rule called the one definition rule. Among other things, this rule specifies that there cannot be multiple definitions of a function across your program. You can't have two translation units that both define a function, otherwise you break this rule. You can think of a translation unit as a .cpp file with all of its headers included into the appropriate places.
So if you have a header file, foo.h, that looks like this:
#ifndef FOO_H
#define FOO_H
int foo() { return 5; }
#endif
And then you include this header in two or more .cpp files, each of the translation units will have their own definition. This violates the one definition rule.
To fix this, your header should give a function declaration like so:
#ifndef FOO_H
#define FOO_H
int foo();
#endif
Then, in the corresponding foo.cpp file, give a definition for the function:
#include "foo.h"
int foo() { return 5; }
This means that only the foo.cpp translation unit will have a definition of foo. Any uses of foo in other translation units will be linked to that definition.
An alternative is to declare the function as inline, as in:
#ifndef FOO_H
#define FOO_H
inline int foo() { return 5; }
#endif
The reason this is allowed is because each translation must be able to see the definition of such a function to be able to inline it. However, I don't recommend using inline all willy-nilly.
Linker errors are not caused by #include errors. Linker errors usually happens when the compilers can't find the definition of something. Or if it finds multiple definitions ( such as in this case )
Check if you are linking with multiple SDL libraries or if you have defined the functions yourself somwhere in the code
possible reason:
define functions in header files. functions should only be defined in .cpp file.
looped header files including. like: a.h includes b.h, b.h includes c.h, and c.h includes a.h. Sometime the looped including is not obvious, but it does happen. "#pragma once" can only prevents one header file from being included more than once, but cannot prevent looped including. To solve this problem, using "forward declaration" to replace some #include statements.
some links about forward declaration:
http://en.wikipedia.org/wiki/Forward_declaration
When can I use a forward declaration?
http://msdn.microsoft.com/en-us/library/f432x8c6(v=vs.80).aspx
I have an MFC application AVT_testapp, and in the header file (AVT_testappDlg.h) I am trying to create a variable outside of all functions, classes, etc. in order to make it global. Whenever I try to do this though (say I try int x = 7), I get the error:
1>AVT_testappDlg.obj : error LNK2005: "int x" (?x##3HA) already defined in
AVT_testapp.obj
1>..\..\bin\x64\Debug\AVT_testapp.exe : fatal error LNK1169: one or more
multiply defined symbols found
Everything I have found on google says "just add header guards". AVT_testappDlg has 6 #include's, and each of them has header guards.
What else could be causing these errors when creating global variables?
EDIT: Here is the beginning of my header file,
#pragma once
#include "../../src/CoreUtils/nierr.h"
#include "..\..\src\CoreUtils\StringHelpers.h" //includes windows.h
#include "afxwin.h"
#include "afxcmn.h"
#include "IFrameObserver.h"
#include "c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\GdiPlusHeaders.h"
//#include <fstream>
//#include <windows.h>
int x = 7;
using namespace AVT::VmbAPI;
//////////////////////////////////////////////////////////////////////////
////////// MyObserver class ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class MyObserver : public IFrameObserver
{
private:
MyObserver( MyObserver& );
MyObserver& operator=( const MyObserver& );
public:
VmbUchar_t* imageData;
//...
//...
//...
//...
//that's the end of the relevant stuff
You cannot define variables at namespace level in a header. In general it is best not to have global variables, but if you need to you should provide only a declaration in the header and the definition in a single .cpp:
//header
extern int i;
//cpp
int i;
The problem with your code is not related to header guards. Header guards ensure that a header is parsed only once in each translation unit. Lack of header guards causes compiler errors, where the compiler sees, say for example a class, defined multiple times in the same translation unit after preprocessing. In your case the error is a linker error LNK2005, and it means that the same symbol was defined in multiple translation units (in your case in each translation unit that includes the header with the definition).
If the global variable is not const(*), you cannot put it in a header file and include it in multiple translation units (i.e. .cpp files). Otherwise, you will end up with multiple definitions of the same symbol in your program, violating the ODR (One Definition Rule, see Paragraph 3.2 of the C++11 Standard), and the linker will complain about that.
You should use the extern modifier in your shared header to provide only a declaration of your variable:
extern int var;
Then, in one single .cpp file, you can provide a definition for it:
int var;
(*) const global variables have internal linkage by default, so each translation unit will end up having a private copy of it and no multiple definition will occur.
if you insist on having a global variable at least put it in a namespace to avoid collisions with other modules
namespace globals
{
extern int x;
}
then in the .cpp file define it.
int globals::x = 0;
it also makes it more clear that it is a global variable.
I am working with form application in VC++. I have main form i.e. Form1.h and also the child form named child.h. I am calling the child.h form on the button click of the form1.h. For calling the child.h I have to include Child.h in Form1.h.
I have used the following code
in Form1.h
#incude "Child.h"
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Child^ c=gcnew Child;
c->Visible=true;
}
And In Child.h I am doing some processing. For this I have made one header file named param.h having some function name and global variables name. I have included param.h in Child.h file.
And param.h is
#ifndef param_h_seen
#define param_h_seen
#define LED_Line 4
#define CALIBRATION_MODE 0
typedef unsigned __int32 uint32_t;
typedef unsigned __int8 uint8_t;
/****for LED ROI entered by user***/
int x_of_roi=6;
int y_of_roi=10;
/********************************/
/*************for graph ROI*******/
int ROIwidth=16;
int ROIheight=4096;
/********************************/
int LED_num= 64;
unsigned short *calib_factor;
/*********functions*****************/
int find_area(unsigned char *intensity,int start);
void DetectRectangle();
/***************************************/
#endif
After Including the child.h It is showing the error
PUMA_LED_TESTER.obj : error LNK2005: "unsigned short * calib_factor" (?calib_factor##3PAGA) already defined in Child.obj
PUMA_LED_TESTER.obj : error LNK2005: "int x_of_roi" (?x_of_roi##3HA) already defined in Child.obj
PUMA_LED_TESTER.obj : error LNK2005: "int y_of_roi" (?y_of_roi##3HA) already defined in Child.obj
PUMA_LED_TESTER.obj : error LNK2005: "int ROIwidth" (?ROIwidth##3HA) already defined in Child.obj
PUMA_LED_TESTER.obj : error LNK2005: "int ROIheight" (?ROIheight##3HA) already defined in Child.obj
PUMA_LED_TESTER.obj : error LNK2005: "int LED_num" (?LED_num##3HA) already defined in Child.obj
I don't know why these errors are coming.Can any body please tell me the solution to solve these errors
Thanks in Advance
int x_of_roi=6;
int y_of_roi=10;
Those are definitions, and should not be in your header files. Place them in one of the cpp files, and on the header have:
extern int x_of_roi
extern int y_of_roi;
Same goes with the rest of the global variables you declare in your header files. When those headers are included by more than one cpp file (namely translation unit), each unit effectively declares new variables with the same name, which the linker complains about.
Each time you #include a header into you source file, the result is the same as just copy/pasting the header's text. So, if you have a header which defines something:
header.h:
int magic = 0xA0B1C2D3
And you include it into multiply cpp files:
source1.cpp:
#include "header.h"
<...>
source2.cpp:
#include "header.h"
<...>
The result is that the variables and macros are being defined for each cpp. In this case, it is ok. But if you have more complicated dependencies, this may result in errors that you are currently getting.
In your case you are basically including the same file twice, and that leads to multiply definitions of stuff with the same name. What you need to do is to place the definitions outside of header files, and use extern when you need to access them from elsewhere.