1

In my VC++ 2008 project, I create two files, Globals.h and Globals.cpp, as follows:

Glboals.h:

#pragma once

extern ULONG g_ulMAPIUnicodeFlag;

Globals.cpp:

#include "StdAfx.h"
#include "Globals.h"
#include <mapidefs.h>

#ifdef _UNICODE

static ULONG g_ulMAPIUnicodeFlag = MAPI_UNICODE;

#else

static ULONG g_ulMAPIUnicodeFlag = 0;

#endif

Then I use the global variable in another file, TestGlboalDlg.cpp, as follows:

#include "Globals.h"

...

void CTestGlobalDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    ULONG a;

    a = g_ulMAPIUnicodeFlag;
}

But get the following link error:

TestGlobalDlg.obj : error LNK2001: unresolved external symbol "unsigned long g_ulMAPIUnicodeFlag" (?g_ulMAPIUnicodeFlag@@3KA)

Why? If I remove the static modifier in GLobals.cpp, then everything is OK. However, static modifier is required since I need to set the value of the flag at the beginning of the program.

Thanks

alancc
  • 487
  • 2
  • 24
  • 68
  • `static`'s purpose on a declaration at namespace scope is exactly to *not* make the declaration visible to other translation units. It does not mean the same as `static` on a declaration inside a class or at block scope. `static` is not required to initialize the variable at program startup. – walnut Dec 18 '19 at 02:51

1 Answers1

2

static is the exact opposite of extern. Do not mix the two.

#ifdef _UNICODE

ULONG g_ulMAPIUnicodeFlag = MAPI_UNICODE;

#else

ULONG g_ulMAPIUnicodeFlag = 0;

#endif
robthebloke
  • 9,331
  • 9
  • 12