Home > Software engineering >  Can API function initialize const global variable?
Can API function initialize const global variable?

Time:09-25

I wrote a program that uses a const global variable, and I wonder if it is ok to initialize it by calling a Windows API function on the global scope, outside of any other function, and outside of main() or WinMain(). It goes something like this:

#include "stdafx.h"
#include <iostream>
#include "windows.h"

const int i_HRes = GetSystemMetrics(SM_CXSCREEN);

int main()
{ std::cout << "Horizontal screen resolution: " << i_HRes << std::endl;
  std::cin.ignore();
  return 0;
}

It compiles and runs without errors, but I wonder if calling an API function on the global scope could cause a problem somewhere down the line in consumer software.

CodePudding user response:

My recommendation is to make the variable accessible, but put the initialization within a function, and use something from the program environment's lifecycle to trigger and initialize when things could be changed. This could be at the beginning of the program, and when the screen resolution is changed. Because it could change, I don't recommend making it constant, either.

However as to making a Windows API call in the global scope, it should be OK from a technical perspective, just make sure you understand WHEN that function is going to be called - during initialization of the program in this case. If you were calling a function that depends on a screen context already being available, or a window being available, it will fail.

CodePudding user response:

In the example you showed, it’s fine. The implicit, compiler-generated code which initialises i_hRes is called in a context where it’s fine to call winapi functions. In general, by the time your program is allowed to do anything, it’s safe to do winapi things.

However, as Raymond mentioned in a comment, that’s specific to the fact that you’re making an executable program. If you were writing a DLL instead, it might be a bad idea to call outside functions.

  • Related