halachkin
halachkin

Reputation: 37

LNK2005, C++/CLI, no idea

I have a pure C++ code, there are two classes: Dictionary and Training. I would like to make a WinForms project using these classes. So, I have two forms and need to share my class member to both, like a global variable. I tried to make it in that way, part of MyForm.h:

//MyForm.h , first(main form)
public ref class MyForm : public System::Windows::Forms::Form
{
private:
    Dictionary *dict;
    Training *train;
    string *fileName;
public:
    MyForm(void)
    {
        InitializeComponent();
        dict = new Dictionary;
        train = new Training;
        fileName = new string;
    }

There is some event:

 private: System::Void exploremanageToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
         msclr::interop::marshal_context context;
         ExploreForm^ eForm = gcnew ExploreForm(dict);
         eForm->Show();
         int rowCount;
         vector<string> str;
         str = dict->getAllWords(inverted);
         eForm->DGV->RowCount = str.size();
         for (int i = 0; i < str.size(); i++)
             eForm->DGV->Rows[i]->Cells[0]->Value = context.marshal_as<String^>(str[i]);
         eForm->buttonDelete->Enabled = false;
         eForm->buttonEdit->Enabled = false;
         eForm->textBoxEdit->Visible = false;


}

Part of the second form:

//ExploreForm.h
public ref class ExploreForm : public System::Windows::Forms::Form
{
private: Dictionary *dict;
public:
    ExploreForm(Dictionary *aDict)
    {
        InitializeComponent();
        dict = aDict;
    }

At all headers, I have #ifndef or #pragma once, but I am still getting strange LNK2005 error.

Full code:

MyForm.h : https://codeo.me/5mO

ExploreForm.h : https://codeo.me/5mI

globals.h: https://codeo.me/5mJ

globals.cpp: https://codeo.me/5mK

Dictionary.h: https://codeo.me/5mL

MyForm.cpp: https://codeo.me/5mP

How can I share my native C++ class member between two forms? I know, that there are a lot of questions about lnk2005, but I really have any ideas.

Upvotes: 1

Views: 253

Answers (2)

0x492559F64E
0x492559F64E

Reputation: 124

In Addition to what David Heffernan said:

Move your definitions out of the .h files and into the .cpp files.

You can also inline those functions or make a template out of them. Either one will then be put in your .h file. However, this produces more overhead, thus larger file sizes.

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 613412

You are defining your methods in the header file. When you include that header file in multiple translation units, that means that there are multiple definitions. That's what the linker is complaining about when it says:

.... already defined ....

Move the definitions of the methods out of the .h files and into the .cpp files.

Upvotes: 4

Related Questions