Search code examples
c++visual-c++uwpglobal-variables

UWP C++: Writing only instead of reading to a global variable?


I have a separate header file for where I declare global variables. I have included that header file in pch.h which is included in every .cpp file. #include "variable.h" I now need to call the variable and read it in an if statment to start some code. Before compilation, no errors are shown in Visual Studio. However, when I compile the code, it returns error:

Error   LNK2005 "bool ahschecked" (?ahschecked@@3_NA) already defined in checkin.xaml.obj   pch.h

The variable is "ahschecked" which is type Boolean and the file I am trying to read the global variable from is checkin.xaml.obj, the original declaration of the variable is in pch.h

This worked before in windows forms but when I transferred over to UWP, I was unable to get it to work.


I have recreated this issue with a smaller program.

Var.h (where the global variable is stored)

#pragma once
extern bool globalbool = false;
#pragma endregion

pch.h (automatically included in every .cpp)

#pragma once
#include <collection.h>
#include <ppltasks.h>
#include "App.xaml.h"
#include "var.h"

MainPage.xaml.cpp (attempting to read from global var)

#incldue "pch.h"
#include "MainPage.xaml.h"

void testapp::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) {
if (::globalbool == false)
{
// do something
}
}

Solution

  • I was able to resolve this issue by declaring the global variable in the header file without any values attached to it then attaching the values to it later outside in the .cpp file.