Can API function initialize const global variable? - c++

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.

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.

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

How to initialize "RInside" instance in a function NOT main function, and call it multiple times without getting "R is already initialized"?

I would like to use RInside in a function that is NOT the main function in my c++ program. After debugging, I found out that the function works for the first round and I get the output as expected but when it is called for the second time my program stops and I get the error message "R is already initialized". Can anybody help me to have a workaround to overcome this issue?
please see below a simple example to clarify that.
I need to call mainR() function from a function(my_func) that is also NOT the main function.I am actually dealing with a bit complex program so my_func will be also called multiple times, which made initializing RInside useless..
Sorry, the code doesn't look realistic but I just wanted to simplify and clarify my question.
#include <RInside.h>
void mainR()
{
RInside R; // create an embedded R instance
R["txt"] = "Hello, world!\n"; // assign a char* (string) to 'txt'
R.parseEvalQ("cat(txt)"); // eval the init string, ignoring any returns
}
void my_func()
{
mainR();
mainR();
.
.
}
It would appear (I am not an expert on RInside) that an application must have no more than one RInside object created over the course of an application's lifetime. This corresponds to C++'s concept of "static storage duration". When a variable is defined in the main function, the difference between "automatic" (the default) and "static" duration is usually insignificant, but it is highly significant for a function called more than once.
Adding the keyword static indicates that a variable is to have static storage duration.
static RInside R; // create an embedded R instance
This has two effects on a variable defined inside a function. First, the object is not destroyed when the function ends. Second, the object is not re-initialized when the function is called again. (It is still initialized when the function is called the first time.) This avoids the error where R was initialized twice. However, it also comes with a caveat—the object retains state between function calls. One must assume that the RInside object might have been used earlier, even at the beginning of mainR().

Extern pointer is null in static library, worked fine when not a static library

I broke my Visual Studio project (2015, C++) into three pieces:
The main application in a static library
The executable which just has a main function
Unit tests which use the static .lib file so that they can import the required classes and do the unit tests on them.
Before I split it into a lib/exe/tests, the main application was just a standalone executable, and it worked perfectly fine.
Now I can't run the executable with only the main function, nor the unit tests as a certain pointer is always null. The only main difference is that I'm using a raw pointer in this example, but I was using a unique_ptr in my code (currently however I switched to the raw pointer just to make sure this following example is as accurate as possible and it didn't magically compile/run properly with the raw pointer).
The code looks very similar to the following (the extra code has been removed):
// console.hpp
extern Console *console;
The implementation cpp file (only of what is needed):
// console.cpp
Console *console = new Console();
Now in some unrelated function, this code fails due to the console pointer being a nullptr:
// some_other_file.cpp
#include "console.hpp"
// Inside some function...
console->doSomething(); // console is NULL
Again, the code I have worked perfectly fine when it was in one project. Regardless, it all compiles fine with no linking errors even though it has been broken into 3 pieces, but now that pointer is always null.
As a last interesting note, the non-pointer variables that are global and extern do work. Is this something limited to pointers/unique_ptrs?
Is this something fixable by a singleton pattern?
The clue is in this comment: "it appears other code is getting called before the main function that don't let the global variable get initialized."
The code referencing console is probably running as part of the initialization of another global and, in this case, is happening before the initialization of console. You have to be very careful to be sure that you're not depending on the order of the global initializers. You were probably getting lucky before you split the program, and now your luck has run out.
The easiest way to fix it is to use a singleton pattern. Instead of having other parts of the program directly reference the pointer, you have them call a function that returns the pointer, and that function will initialize it the first time. This ensures that it's initialized before it's used.
Here's a common pattern for it:
Console *GetConsole() {
static Console *console = new Console();
return console;
}
Now console is no longer a global variable. Everything that wants to access the console calls GetConsole instead.
The function-local static variable will be initialized the first time the function is called, and after that it just returns the value. If you have multiple threads and an older compiler, you have to do more work to protect against a possible race condition. Modern compilers should do the initialization in a thread-safe way.

Why must c++ statements be contained within functions?

As a newbie to c++, coming from python, I'm not sure why c++ doesn't allow statements outside of a function (in the global namespace?). It seems like this could be useful to do some initialization before main() is called or other functions are even declared. (I'm not trying to argue with the compiler, I'd just like to know the thought process behind implementing it this way.)
When you're running a python program, the interpreter runs through it from top to bottom executing as it goes. In C++, that doesn't happen. The compiler builds all your functions into little blobs of machine code and then the linker hooks them up. At runtime, the operating system calls your main function, and everything goes on from there. In that context, code outside of functions is meaningless - when would it run?
This can be thought of as a style difference between C++ and Python. However, there are pretty good reasons for it too. In C and C++, there is a very clear and specific place that the execution of your code starts from, and that's the beginning of the main() function (of course, this is only an approximation of the truth, but we can ignore that for now.) Actually, a C/C++ program starts and ends with the main() function which - in my opinion - helps quite a lot when you want to understand what a program actually does. The high-level flow of the program is clearer. Contrast this with the alternative; with code scattered all through the file and in between functions and whatnot.
Even in a well-organized and non-trivial Python program, you put your main body of code under an if __name__ == "__main__":, don't you?
Now for some stuff that are a little bit more advanced. There are ways for code to run before the main() function is called. Here's one of them:
#include <iostream>
using namespace std;
bool RunBeforeMain ()
{
cout << "Before main()!" << endl;
return true;
}
// This variable here causes the above function to be called
bool ignore_this_variable = RunBeforeMain ();
int main ()
{
cout << "Start of main()" << endl;
return 0;
}
Also, the constructors of all the global variables and all the static members of classes and some platform-dependent stuff are run before main(). Analogously, there are ways for code to run after the main() is finished. Those are usually the destructors for objects constructed before main() began, and functions registered with the atexit() function.
The main() is the access point to the program. So any code you wanna write would be needs to have an order of execution from that point.
Static variables are initiated before the main() is executed, so you can initiate whatever variables you need before that.
But if you want run code that initiates the state of the program, you should do it just in the beginning of the program, and abuse the static variables and do it some constructor.

how to start the execution of a program in c/c++ from a different function,but not main() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the program execution always start from main in C?
i want to start the execution of my program which contains 2 functions (excluding main)
void check(void)
void execute(void)
i want to start my execution from check(), is it possible in c/c++?
You can do this with a simple wrapper:
int main()
{
check();
}
You can't portably do it in any other way since the standard explicitly specifies main as the program entry point.
EDIT for comment: Don't ever do this. In C++ you could abuse static initialization to have check called before main during static init, but you still can't call main legally from check. You can just have check run first. As noted in a comment this doesn't work in C because it requires constant initializers.
// At file scope.
bool abuse_the_language = (check(), true);
int main()
{
// No op if desired.
}
Various linkers have various options to specify the entry point. Eg. Microsoft linker uses /ENTRY:function:
The /ENTRY option specifies an entry point function as the starting
address for an .exe file or DLL.
GNU's ld uses the -e or ENTRY() in the command file.
Needles to say, modifying the entry point is a very advanced feature which you must absolutely understand how it works. For one, it may cause skipping the loading the standard libraries initialization.
int main()
{
check();
return 0;
}
Calling check from main seems like the most logical solution, but you could still explore using /ENTRY to define another entry point for your application. See here for more info.
You cannot start in something other than main, although there are ways to have some code execute before main.
Putting code in a static initialization block will have the code run prior to main; however, it won't be 100% controllable. while you can be assured it runs prior to main, you cannot specify the order that two static initialization blocks will run prior to them both executing before main.
Linkers and loaders both have the concept of main held as a shared "understood" start of a C / C++ program; however, there is code that runs prior to main. This code is responsible for "setting up the environment" of the program (things like setting up stdin or cin). By putting code in a static initialization block, you effectively say, "hey you need to do this too to have the right environment". Generally, this should be something small, that can stand independently in execution order of other items.
If you need two or three things to execute in order before main, then make them into proper functions and call them at the beginning of main.
There is a contrived way to achieve that, but it is nothing more than a hack.
The idea is to create a static library containing the main function, and make it call your "check" function.
The linker will resolve the symbol when linking against your "program", and your "program" code will indeed not have a main by itself.
This is NOT recommended, unless you have very specific needs (an example that pops to mind is Windows Screensavers, as the helper library that comes with the Windows SDK has a main function that performs specific initialization like parsing the command line).
It may be supportted by the compiler. For example, gcc, you can use -nostartfiles and --entry=xxx to set the entry point of the program. The default entry point is _start, which will call the function main.
You can "intercept" the call to main by creating an object before the main starts. The constructor needs to execute your function.
#include <iostream>
void foo()
{
// do stuff
std::cout<<"exiting from foo" <<std::endl;
}
struct A
{
A(){ foo(); };
};
static A a;
int main()
{
// something
std::cout<<"starting main()" <<std::endl;
}
I have found solution to my own question.
we can simply use
#pragma startup function-name <priority>
#pragma exit function-name <priority>
These two pragmas allow the program to specify function(s) that should be called either upon program startup (before the main function is called), or program exit (just before the program terminates through _exit).
The specified function-name must be a previously declared function taking no arguments and returning void; in other words, it should be declared as:
void func(void);
The optional priority parameter should be an integer in the range 64 to 255. The highest priority is 0. Functions with higher priorities are called first at startup and last at exit. If you don't specify a priority, it defaults to 100.
thanks!

unwanted constructor calls before main()

I am working on some multi-thread code with pthreads. When I discovered some memory-leaks (via valgrind), I simply added some
cout << " new [some name of class for me]" << endl;
in part of constructors, because I thought I have removed all of them. This revealed that part of them are launched before main(). I have removed everything from main(), so it looks like:
int main(){
return 0;
}
Even without any #includes those constructors are still invoked. I think nothing from the previous code should be invoked in this case. I used "project clean" option in eclipse and try to delete binaries (Debug/Release). Nothing helps ..
What is the purpose of that? What else I can do?
Thanks in advance.
global and static variables are initialized before main. Except for the static variables declared inside a function. They are initialized on a first call. So I think you should look at the static and global variables