从函数访问表单的属性

时间:2011-10-16 12:36:57

标签: .net visual-studio c++-cli

我一直在寻找解决这个问题的方法已有一段时间了。我所拥有的是标准的Form1.h,其中声明了一些全局变量。我想从单独的.cpp文件中的函数访问此表单的属性。所以这就是我试图实现这个目标的方法:

//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!";
    }
}

这段代码给了我LNK2005已经定义的错误,我知道这是因为我在test.cpp中包含Form1.h时重新声明了我的变量。我可以找到解决此问题的方法吗?还是应该删除变量?

1 个答案:

答案 0 :(得分:1)

你的一个.cpp文件应声明没有“extern”的变量,你的.h文件应该用“extern”声明它们