Taylor Scanlon
Taylor Scanlon

Reputation: 70

Global scope LPWSTR reverts after changing it

This may be a really silly question but it's something I've been struggling with. After changing the LPWSTR in a method it appears to only be changing for that specific method and reverting back immediately after. I know global variables are evil but this is not my choice because it would require changing quite a bit of code. Here's an example of what I'm doing:

Test.h

static LPWSTR globalStr = L"This shouldn't be here.";

// The ...s are irrelevant code.
class Test {
    public:
        ...
        void changeGlobalStr();
        void testMethod();
        ...
    ...
};

Test.cpp

#include "Test.h"

Test::changeGlobalStr() {
    string testString("This should be here.");

    // I manipulate testString over the next few lines so a variable is necessary.
    ...

    BSTR bConversion = _com_util::ConvertStringToBSTR(testString.c_str());
    globalStr = bConversion

    // This prints out the correct output.
    wcout << "globalStr in changeGlobalStr(): " << globalStr;
}

SecondTest.cpp

#include "Test.h"

Test::testMethod() {
   changeGlobalStr();
   // Get correct output from the print inside the method.
   wcout << "globalStr in testMethod(): " << globalStr;
   // Now incorrect output is printed.
}

testMethod() ends up printing out "This shouldn't be here" instead of "This should be here". I'm not entirely sure what I'm doing wrong but I feel like it's something elementary and I'm just very rusty in my C++.

Upvotes: 2

Views: 184

Answers (2)

Pete Becker
Pete Becker

Reputation: 76438

Yes, indeed, the text in the LPWSTR is correct: "This shouldn't be here." The problem is that globalStr isn't global. It's defined as static in the header, so each source file gets its own copy of globalStr. Changing it in one source file doesn't change it in any of the others.

To fix it, give it an extern declaration in the header and define it in one source file:

// Test.h:

extern LPWSTR globalStr;

// Test.cpp:

LPWSTR globalStr = L"This shouldn't be here."

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409356

When using static on a global variable, it no longer is global. It's defined only in the translation unit (i.e. source file) where it's declared. This means that if you declare a static variable in a header file and include that in several source files, each source fill will have one unique variable each.

Maybe you mean to use extern instead?

Upvotes: 1

Related Questions