I’ve been looking for ways of solving this problem for quite some time now. What I have is a standard Form1.h with some global variables declared in it. I want to access the properties of this form from a function in a separate .cpp file. So here is how I try to accomplish this:
//Form1.h
#pragma once
#include "stdafx.h"
#include "test.h"
unsigned char vMAC1;
unsigned char vMAC2;
unsigned char vMAC3;
unsigned char vMAC4;
unsigned char vMAC5;
unsigned char vMAC6;
extern long pNum;
//ARP Variables
unsigned char gMAC1;
unsigned char gMAC2;
unsigned char gMAC3;
unsigned char gMAC4;
unsigned char gMAC5;
unsigned char gMAC6;
extern unsigned char mMAC1;
extern unsigned char mMAC2;
extern unsigned char mMAC3;
extern unsigned char mMAC4;
extern unsigned char mMAC5;
extern unsigned char mMAC6;
namespace Artemis_v {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Runtime::InteropServices;
using namespace System::Threading;
using System::IntPtr;
/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
protected:
///// And so on just standard compiler-created statements..
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
ChangeText(this);
}
// test.h
#ifndef TEST_H
#define TEST_H
namespace Artemis_v
{
ref class Form1;
void ChangeText(Form1 ^frm);
}
#endif
// test.cpp
#include "StdAfx.h"
#include "test.h"
#include "Form1.h"
namespace Artemis_v
{
void ChangeFormText(Form1 ^frm)
{
frm->Text="Hello!";
}
}
This code gives me LNK2005 Already defined errors and I know it’s because of my variables being redeclared when I include Form1.h in test.cpp. Can I find any workarounds to this problem or should I remove the variables?
One of your .cpp files should declare the variables without “extern” and your .h file should declare them with “extern”