如何将变量用作全局变量?

时间:2015-11-27 13:50:45

标签: c++ imagemagick

我可以使用类成员变量作为全局吗?

我想将类成员变量用作全局,如下所示。

// mfc_test5Dlg.h : header file
//

#pragma once
#include "afxcmn.h"
#include "Testview.h"
#include "atltypes.h"

Image m_image;<------------------HERE!!!
Image m_blurgray;<------------------HERE!!!


// Cmfc_test5Dlg dialog
class Cmfc_test5Dlg : public CDialogEx
{
...

// Testview.cpp : implementation file
//

#include "stdafx.h"
#include "mfc_test5.h"
#include "mfc_test5Dlg.h"

extern  char * fileposition;
extern int slider_val;

// CTestview
CTestview *global_TestView; 

IMPLEMENT_DYNCREATE(CTestview, CScrollView)

    CTestview::CTestview()
{
    global_TestView = this;
}

CTestview::~CTestview()
{
}


BEGIN_MESSAGE_MAP(CTestview, CScrollView)
END_MESSAGE_MAP()


// CTestview drawing

void CTestview::OnInitialUpdate()
{
    CScrollView::OnInitialUpdate();

    CSize sizeTotal;
    // TODO: calculate the total size of this view
    sizeTotal.cx = sizeTotal.cy = 100;
    SetScrollSizes(MM_TEXT, sizeTotal);


}

void CTestview::OnDraw(CDC* pDC)
{
    CDocument* pDoc = GetDocument();
    // TODO: add draw code here

        CRect rcWin;
GetWindowRect( &rcWin );
int ff;
ff=rcWin.Width();
rcWin.Height();

m_image.read("file"); <------------------HERE!!!
    DoDisplayImage();

但是我发现了一些错误。

------ Build started: Project: mfc_test5, Configuration: Release Win32 ------

InitializeBuildStatus:
  Touching "Release\mfc_test5.unsuccessfulbuild".
ClCompile:
  All outputs are up-to-date.
  All outputs are up-to-date.
  All outputs are up-to-date.
ResourceCompile:
  All outputs are up-to-date.
mfc_test5Dlg.obj : error LNK2005: "class Magick::Image m_image" (?m_image@@3VImage@Magick@@A) already defined in mfc_test5.obj
mfc_test5Dlg.obj : error LNK2005: "class Magick::Image m_blurgray" (?m_blurgray@@3VImage@Magick@@A) already defined in mfc_test5.obj
Testview.obj : error LNK2005: "class Magick::Image m_image" (?m_image@@3VImage@Magick@@A) already defined in mfc_test5.obj
Testview.obj : error LNK2005: "class Magick::Image m_blurgray" (?m_blurgray@@3VImage@Magick@@A) already defined in mfc_test5.obj
C:\work\mfc_test5\mfc_test5\Release\mfc_test5.exe : fatal error LNK1169: one or more multiply defined symbols found

Build FAILED.

Time Elapsed 00:00:01.94
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

正如您可以看到上面的代码,我想使用m_image作为全局类成员变量。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用extern关键字

在标头中声明您的变量
extern Image m_image;
extern Image m_blurgray;

在.cpp(源)文件中定义这些变量。

Image m_image;
Image m_blurgray;