Linker error: _main already defined in *.obj - c++

The following code structure:
ArrayStack.h
#ifndef ARRAY_STACK_H
#define ARRAY_STACK_H
#include "Array.h"
// class ArrayStack
#endif
ArrayStack.cpp
#include "ArrayStack.h"
// ArrayStack's methods
Array.h
#ifndef ARRAY_HEADER
#define ARRAY_HEADER
#include <iostream>
// class Array
#endif
Array.cpp
#include "Array.h"
// Array's methods
main.cpp
#include "ArrayStack.h"
int main() {
return 0;
}
generates these errors:
LNK1169 one or more multiply defined symbols found
LNK2005 _main already defined in Array.obj
What's the problem here? Please do note that Array.cpp did have int main() defined in itself when it was included in the project for the first time, but no longer has it (neither does the ArrayStack.cpp). Also, the code compiles just fine when the int main() in main.cpp is omitted...

The error message means that in all the compiled code, the *.obj files, the linker finds more than one main() function. One is obviously in main.cpp.
The first solution that comes to mind, as mentioned in comments, is to (enforce) re-compile by somehow deleting the *.obj files.
When this doesn't change anything try to rebuild your solution separately from scratch. Start with main.cpp without the include. Then successively add files where you are confident that you won't get errors. Maybe you have to comment out some lines in some cases to make compilation possible.

Related

How to link multiple .cpp files in Code::Blocks for a single project?

While following the book C++ For Dummies, I have three files in my CodeBlocks project, main.cpp, Pen.h, and Pen.cpp. They look like this:
main.cpp:
#include <iostream>
#include "Pen.h"
//#include "Pen.cpp"
using namespace std;
int main()
{
Pen MyPen = Pen();
MyPen.test();
}
Pen.h:
#ifndef PEN_H_INCLUDED
#define PEN_H_INCLUDED
//#include "Pen.cpp" // Uncommenting this gives a different error
using namespace std;
class Pen
{
public:
// attributes omitted
// PROTOTYPES:
// other functions omitted
void test();
};
#endif // PEN_H_INCLUDED
Pen.cpp:
#include <iostream>
#include "Pen.h"
using namespace std;
//other function definitions omitted
void Pen::test()
{
cout << "Test successful." << endl;
}
When I run the code as listed above, I get an "undefined reference to `Pen::test()'" error. To fix this, I changed the #include statements at the top of main.cpp to:
#include <iostream>
//#include "Pen.h"
#include "Pen.cpp"
This works as intended and correctly prints out "Test successful."
My question is this: what in the world is the point of putting a function prototype in a header file if I have to import the .cpp file later on anyways?
EDIT: It turns out this was a problem with not knowing how to use Code::Blocks rather than with the C++ language.
Assuming you're using gcc, you can compile and link in one step by supplying multiple .cpp files via the command line.
g++ Pen.cpp main.cpp
clang should be similar.
clang++ Pen.cpp main.cpp
An #include should never reference a .cpp file. At all. There's no good reason to do it. Include your headers and then supply the names of all .cpp files when you compile. If your project gets big and you have too many .cpp files to reasonably list, then it's time to break out a makefile or similar.
In the main.cpp include the header file:
#include "Pen.h"
The Pen.h file it's ok.
You need to add the Pen.cpp file to the project tree.
Go to Project -> Add files... and add Pen.cpp

One time included .h functions already defined in main.obj

Ok so, simply said : I've included a .h into another .h and i get a compilation error telling me that the functions are already defined in main.obj
But, well i've only included Graphics.h one time so how can it be possible that main.obj also defined the Graphics.h functions ?
I got an Error LNK2005 "Already defined in main.obj".
Graphics.h contain functions that many others files will need, but for the moment we have a problem with just one file so I'd like to fix that first.
EDIT : SOLVED by spliting the header, i kept the header for the functions prototypes and I created a new Graphics.cpp for the functions definition
Here are the most concerned files, I've commented the files content so it is readable.
If I'm wrong by commenting please tell me and I'll put it on pastebin or something like that
main.cpp
#include "main.h"
using namespace std;
int main()
{
sMainData data = {};
main_Initialize(data);
while (data.config.window.isOpen())
{
main_Event(data);
main_Update(data);
main_Draw(data);
}
return 0;
}
main.h file :
#ifndef MAIN_H
#define MAIN_H
#include <SFML/Graphics.hpp>
#include "PlayerClass.h"
// Structures...
// Prototypes...
// Functions...
#endif // !MAIN_H
PlayerClass.h file :
#ifndef PLAYERCLASS_H
#define PLAYERCLASS_H
#include "AliveClass.h" // Including the mother
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include "Graphics.h" // <-- So here we have our man
//Class definition
#endif // !1
Graphics.h file :
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "SFML/Graphics.hpp"
// Prototypes...
// Functions...
#endif // !GRAPHICS_H
You didn't provide a minimal reproducible example, but my best guess is, you have some function implemented in the header file, while ending up including that header, either directly or indirectly, in more than one cpp file. The result is exactly the same function with exactly the same signature, being compiled in both cpp files, which causes the linker to complain.
Solutions:
Move the function out of the header and into its own cpp file (probably the best)
Find a way to only include the header in one single cpp file (probably the second best in case the header isnt yours and you don't want to touch it)
Make that function inline (probably the easiest, but technically the worst)

How to properly include Header and Implementation Files?

I am a novice programmer in c++, and I am currently getting a compiling error
Undefined symbols for architecture x86_64
Supposedly this originates from how the header files and implementation files are included/coded.
Below is some code that generates the compiling error I am receiving
Main
//Main.cpp
#include <iostream>
#include <string>
#include "Animal.hpp"
using namespace std;
int main(){
Animal myPet;
myPet.shout();
return 0;
}
Header
//Animal.hpp
#ifndef H_Animal
#define H_Animal
using namespace std;
#include <string>
class Animal{
public:
Animal();
void shout();
private:
string roar;
};
#endif
Implementation
//Animal.cpp
#include "Animal.hpp"
#include <string>
Animal::Animal(){
roar = "...";
}
void Animal::shout(){
roar = "ROAR";
cout << roar;
}
This code generates my compiling issue. How would this issue be resolved?
Thanks for your time
EDIT
Undefined symbols for architecture x86_64:
"Animal::shout()", referenced from:
_main in test-5f7f84.o
"Animal::Animal()", referenced from:
_main in test-5f7f84.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
maybe you might want to see an alternative set of your 3 files, where things are a little more "sorted", you know, where things are put at places where they "really" belong to.
So here's the "new" header file ..
//Animal.hpp
#ifndef H_Animal
#define H_Animal
#include <string> // suffices
// Interface.
class Animal {
std::string roar; // private
public:
Animal();
void shout();
};
#endif
then the source file ..
//Animal.cpp
#include "Animal.hpp"
#include <iostream> // suffices
// Constructor.
Animal::Animal()
:
roar("...") // data member initializer
{}
// Member function.
void Animal::shout() {
roar = "ROAR";
std::cout << roar;
}
and the main program ..
//Main.cpp
#include "Animal.hpp"
int main(){
Animal thePet;
thePet.shout(); // outputs: `ROAR'
}
plus a little GNU makefile ..
all: default run
default: Animal.cpp Main.cpp
g++ -o Main.exe Animal.cpp Main.cpp
run:
./Main.exe
clean:
$(RM) *.o *.exe
Kick-off things typing just "make" in your cmd-line. Did you like it? --
Regards, M.
I can only find one error in your code and your compiler should have told you that one.
In Animal.cpp, you are using std::cout but you're not #includeing <iostream>. You #include it in Main.cpp but it is not needed there.
If you (really) want to refer to std::cout as cout in Animal.cpp, you also have to add a using namespace std directive in that file.
The using directive in the header file (Animal.hpp) is evil. Get rid of it and type std::string instead. Putting using directives into headers litters the namespaces of all files that use it.
I also don't understand your intentions with the roar member. What is the point of assigning "..." to it in the constructor and re-assigning "ROAR" to it every time shout is called? Couldn't you do without that variable and simply have
void
Animal::shout()
{
std::cout << "ROAR\n";
}
? I have added a newline because you'd probably want one.
The main issue I was having with this coding project was solved by #JamesMoore.
"#Nicholas Hayden Okay if you have three files, test.cpp(which has main), animal.cpp, and animal.hpp. The command should be g++ animal.cpp test.cpp. You need to compile all source files."
I am currently not using an IDE. So, when I was calling the compiler to compile my main.cpp - It was an issue of compiling the implementation file.
g++ test.cpp
needed to become
g++ test.cpp animal.cpp
This would call the compiler to compile everything the program needed.

Order of including the header file

I am getting linking error in the following program.
//FILE: CDummyMessage.h
#idndef DUMMY_FILE
#define DUMMY_FILE
#include "stdafx.h"
class CDummyMessage(){
static int objCount1;
std::string;
};
#endif //DUMMY_FILE
// CDummyMessage.cpp
all the necessary definition
//main cpp file: SmartPointerExample.cpp
#include "stdafx.h"
#include "CDummyMessage.h"
int main(){
CDummyMessage* OBJ1= new CDummyMessage();
}
I am getting this linking error:-
Error 1 error LNK2005: "private: static int dummy::CDummyMessage::ObjCount1" (?ObjCount1#CDummyMessage#dummy##0HA) already defined in DummyMessage.obj C:\Users\Veil\Documents\Visual Studio 2012\Projects\SmartPointerExample\SmartPointerExample\SmartPointerExample.obj
I am not able to figure out the reason of this linking error. I have made use of #ifndef directive that prevents duplicate inclusion of header file.
I think you have another file called CDummyMessage.cpp in your project ? and Visual studio Compiled that one too.

LNK2005, "already defined error" linker error in MSVC2010

I am trying to implement a test project using the Point Cloud Library and OpenCV with multiple files. When I try to compile, I get the "already defined error" message. Probably I'm doing something stupid that cannot realize for some reason - I tried out a couple of solutions found here, none of them seemed to be help in my case.
What I have:
A libs.h file, where I load the lib files (in Project properties, I only set up the .lib paths and load the libs "by hand", like the headers):
#pragma once
#ifndef PCLTEST_LIBS
#define PCLTEST_LIBS
#ifdef _DEBUG
#pragma comment(lib, "pcl_apps-gd.lib")
#pragma comment(lib, "pcl_common-gd.lib")
// a bunch of other debug libs
#else
// the release libs
#endif
#endif
A main file from which I basically deleted everything at this point to debug:
// load the libs
#ifndef PCLTEST_LIBS
#include "libs.h"
#endif
// pcltest includes
// if only this first one is #included, everything is OK
#include "opencvOperations.h"
// #including this one causes the error
#include "files.h"
// these ones are not working also
//#include "cloudOperations.h"
//#include "visualize.h"
// c++ headers
#include <stdio.h>
#include <string>
//#include <sstream>
//#include <iostream>
void writeInfo()
{
// some std::cout calls
}
int main( int argc, char* argv[] )
{
writeInfo();
// this function is in opencvOperations.h and works OK
pcltest::openLena();
}
Then I get several error messages in my main.obj that some (PCL related) symbols are already defined in files.obj. I use PCL related calls both in opencvOperations and files, the first one is OK, the second one does not work.
Edit:
To add more detail, my files.h header:
#pragma once
#ifndef PCLTEST_FILES
#define PCLTEST_FILES
// pcl headers
#ifndef PCL_COMMON_H_
#include <pcl/common/common_headers.h>
#endif
#ifndef PCL_IO_FILE_IO_H_
#include <pcl/io/file_io.h>
#endif
#ifndef PCL_IO_PCD_IO_H_
#include <pcl/io/pcd_io.h>
#endif
#ifndef PCL_IO_PLY_IO_H_
#include <pcl/io/ply_io.h>
#endif
// boost headers
#ifndef BOOST_FILESYSTEM_OPERATIONSX_HPP
#include <boost/filesystem/operations.hpp>
#endif
#endif
namespace pcltest
{
// function to open PCL or binary PLY files
pcl::PointCloud<pcl::PointXYZ>::Ptr openCloud(std::string filename);
// function to save the point cloud to PCD format
void saveCloud();
}
Before splitting the code into separate files, everything worked well (with the same project settings).
Edit2:
I located the source of the problem,
#include <pcl/io/ply_io.h>
causes this. For now, I got rid of everything related to PLY and everything works fine. I'll look at it later, this might be a PCL library specific issue. Still strange to me why this call causes linker error in an other file, where I don't even use PLY related functions/variables.
I had the same problem as you had. I had a surface.h and surface.cpp file, and I found out that I had to include the ply_io.h file from surface.cpp rather than surface.h and now it compiles fine. I hope that helps or makes sense! haha
If a constant is being instantiated in an include one can also use selectany, per http://msdn.microsoft.com/en-us/library/5tkz6s71%28v=vs.80%29.aspx -- in my case:
const int CSdata[] = {1, 2, 3, 4};
when included in more than one source part produces LNK2005 at link time, avoided via:
const __declspec(selectany) int CSdata[] = {1, 2, 3, 4};
Non-portable, yeah ...