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

倾然丶 夕夏残阳落幕 提交于 2020-01-06 06:26:26

问题


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
}
}

回答1:


I would guess that you didn't declare the global variable as extern but without seeing any code it's hard to be sure.

You should declare your global variables as extern in a header file, and then in one source file you should also define the global variable without extern.

This way of declaring and defining global variables is correct for any C++ program. It makes no difference whether you are writing a windows forms program or a UWP program.

Since you have a header file for global variable declarations, it would also make sense to have a source file for global variable definitions as well.




回答2:


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.



来源:https://stackoverflow.com/questions/54956075/uwp-c-writing-only-instead-of-reading-to-a-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!