User forums > Help

Linker multiple definitions

(1/2) > >>

sggarps:
Hi everyone,

I've recently been having linker problems when compiling projects with classes. The linker (GNU's LD i believe) delcares that member functions have been defined multiple times, and I cannot see any apparent reason for this.

To test the problem, I created a small project with a single basic class, with the declaration and definition in separate ".h" and ".cpp" files respectively. I've coded for the whole "#ifndef" thing in both files. The main() function simply creates an instance of the object, performs a few functions, and outputs a result. However, on compilation of the project, the linker tells me that I have multiple definitions of all my member functions. I've had this happen with other projects with classes in as well. The really weird thing is that when i compile it with g++ from the command line, the project compiles successfully and everything works fine.

I've tried LD's option to allow multiple definitions but this didn't work for some reason. I will post source code here ASAP, but at the moment I'm away from my home computer so you will have to bear with me. Oh and I'm running this all on Win XP Pro SP3 if that's worth anything.

Any ideas on what I need to do to get this to work?

sggarps:
Source code:

main.cpp:

#include <iostream>
#include "class.cpp"

using namespace std;

int main()
{
    /*myClass a;

    for (int i=0;i<10;i++)
    {
        a.Increment();
    }

    for (int i=0;i<3;i++)
    {
        a.Decrement();
    }
    cout << a.Value() << endl;*/
    return 0;
}

class.h:

#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED

class myClass
{
    int m_x;

public:
    myClass(int x);
    myClass();
    ~myClass();
    void Increment();
    void Decrement();
    int Value();
};

#endif // CLASS_H_INCLUDED

class.cpp:

#ifndef CLASS_CPP_INCLUDED
#define CLASS_CPP_INCLUDED

#include "class.h"

myClass::myClass(int x)
{
    m_x = x;
}

myClass::myClass()
{
    m_x=0;
}

myClass::~myClass()
{
}

void myClass::Increment()
{
    m_x++;
}

void myClass::Decrement()
{
    m_x--;
}

int myClass::Value()
{
    return m_x;
}

#endif // CLASS_CPP_INCLUDED

thomas:
Gnu ld is correct (as was to be expected). You compile the class sourcefile twice by adding it to the project and including it from the main file.

sggarps:
But I've tried commenting out the include and was then told the class wasn't defined at all. I always thought you had to include all source files  :?...

sggarps:
If it's worth anything I also tried compiling projects in Dev-C++ with classes and recieved the same problem.

Navigation

[0] Message Index

[#] Next page

Go to full version