I am attmepting to declare boost ptime at the global level. However I am encountering the following issue:
Before the main function I declare:
static boost::posix_time::ptime start_time;
Then inside the main function I initialize:
boost::posix_time::ptime start_time(boost::posix_time::microsec_clock::universal_time());
Then in a function outside the main function, I tried to convert to a string and print and I get "not-a-date-time";
Either the global variable is not being initialized or there is a scope problem?
Thank you for your help.
You define a local variable inside the main function, one that shadows the global variable but has nothing to do with the global variable.
You should not define the variable in the main function, only assign to it:
start_time = boost::posix_time::microsec_clock::universal_time();
boost::posix_time::ptime start_time(boost::posix_time::microsec_clock::universal_time());
Is not going to initialize start_time from the global scope. This is going to create a new variable named start_time that is scoped to main and hides the global start_time. When you try to use the global start_time in another function you get a not-a-date-time error because start_times was never initialized with an actual date.
You either need to do the initialization in the global space, do an assignment in main, or get rid of the global variable, declare it in main, and pass it by reference to the functions that need it. Personally I would go with the last option if possible as globals make the code harder to reason about.
Related
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().
I have a nested if in Lua. I have a variable inside the second if layer that I want to use in the first layer.
The variable is npcSpecimen.
if conditions then
local npcType = util.pickRandom(self.npcTypes)
local npcSpecimen = ""
if npcType == "spacebandit" then
local npcSpecimen = util.pickRandom(self.npcSpecies)
else
local npcSpecimen = util.pickRandom(self.npcSpeciesMutant)
end
local npcId = space.spawnNpc(spawnPosition, npcSpecimen, npcType)
end
If written this way, npcSpecimen will remain empty because the variable set within the if npcType remains only within that chunk. So to alleviate this, I could use global variable instead:
if npcType == "spacebandit" then
npcSpecimen = util.pickRandom(self.npcSpecies)
else
npcSpecimen = util.pickRandom(self.npcSpeciesMutant)
end
However according to the documentation, using global variable isn't the best practice and it's slower.
So what would be the best way to approach this so I could pass npcSpecimen to npcId?
Technically the answer is no, you can't use a local variable outside its scope, that's the whole point of local variables. However, you can just change the scope of the variable by declaring it outside of the block where you're using it:
local foo
if io.read() == "hello" then -- Just a dumb example condition :)
foo = "hello" -- This is not a global, as it was declared local above
end
print(foo)
However, note that the the following doesn't work, or, more precisely, doesn't do the same as the above:
local foo
if io.read()=="hello" then
local foo = "hello" -- This is another local
end
print(foo) -- This will *always* print nil
I have several functions in a program I'm writing that use a value I need to calculate with a very slow function. This value will change every time the program is rerun, so I can't just store a static value. Below is an example.
void this_gets_called_frequently()
{
static int value = slow_function();
//do stuff with the above value
}
My main problem here is not one of the program not working, rather of neatness. I don't really want to initialise a global variable and store the value in that, since it is not going to change once calculated. Would using the static keyword in the manner shown above only call the function above to be calculated once? Would a const keyword added in there help?
Thanks everyone, this was answered perfectly!
Yes, an initialization of local static variable will happen at most once (although I recall some compiler versions could have problems with multithreading here).
const is not required, in this case it's mostly a matter of readability and taste.
Would using the static keyword in the manner shown above only call the function above to be calculated once?
Yes, on the first invocation of this_gets_called_frequently
Would a const keyword added in there help?
No. But add const for documentation value.
Use may use the thread local variables from C++11, if they are available in your compiler. If you are on Windows, you can use similar TlsAlloc API. It is there since the dawn of Win32.
I am trying to create a global variable in a function pass. The code is
gVar= new GlobalVariable(
/*Type=*/Int32Type,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::CommonLinkage,
/*Initializer=*/0, // has initializer, specified below
/*Name=*/"gVar",
/*ThreadLocalMode*/GlobalVariable::InitialExecTLSModel);
However, I keep getting the following compiler error:
error: no matching function for call to ‘llvm::GlobalVariable::GlobalVariable(const llvm::Type*&, bool, llvm::GlobalValue::LinkageTypes, int, const char [4], llvm::GlobalVariable::ThreadLocalMode)’
Could you please tell me the right way to declare a global variable in llvm? Thank you very much!
In addition, I've referred to the header file:
http://llvm.org/docs/doxygen/html/GlobalVariable_8h_source.html
and this post
How can I declare a global variable in LLVM?
You need to pass a Module to the constructor. There are plenty of examples in the LLVM code base for creating global vars. For example, in examples/ExceptionDemo/ExceptionDemo.cpp:
new llvm::GlobalVariable(module,
stringConstant->getType(),
true,
llvm::GlobalValue::LinkerPrivateLinkage,
stringConstant,
"");
By the way - important note: you should not be creating new globals or doing anything else that modifies a module in a function pass. If you have to do that, you need a module pass.
If I have the following code in a function, I will not get an error and I can compile no problem, however, once I put it in global scope I will get an error for "cannot allocate an array of size zero", along with several other errors. Why does this happen and how can I get rid of the errors. I am aware of the risk of global variables, this is just a simple test case.
int* intest[2];
intest[0] = new int;
You are allowed declarations in global scope but not allowed to use the new operator or the assignment. Thus you need the declaration int *intest[2] in global scope (and all your code would see it) but C++ requires the new to be in the sequence of your main code. (probably in some sort of start up function for the app).
EDIT: as pointed out by #phresnel you can use the new operator in this scope but not the assignment (this is unusual but not illegal). However the following new operators used as initiation will work for you:
int *x[2]={new int,new int};
In general the use of such a global buffer is highly discouraged and is considered an anti-pattern - if you can avoid using it you probably should.
int* intest[2];
Is valid placing in the local scope however :
intest[0] = new int;
is not.
The difference is that the upper one is a initalisation statement (creating the variable) and the lower one is a executed code segment.
Code that should be "executed" cant be called in the global scope, for example you cant call a function in the global scope. When would that function be called?
I can create how many variables i want in the global scope but i cant run code from it except from constructors being called when initialisating the global variables.
If you want to execute code such as :
intest[0] = new int;
You would have to execute it trough main or another function, otherwise the program would not know when to execute it.
AFAIK, the global scope only allow u put define and declaration on it. Whereas intest[0] = new int; is a assignment that c/c++ compiler shall fail while compile.