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.
Related
Can you please upvote this post since others show interest in answering and commenting on it? The guy who likes to devote things clearly doesn't know how to remove devoting or upvote a post back.
I'm trying to use labels in my project but when I jump over a set of instructions using goto to transfer control to another section of the code, I get this error that says: transfer control bypasses initialization of (certain variables).
This is the code that produces the error:
goto label1;
label00:
int a = 0;//the compiler can't let me skip this line
int b; // but this line is fine to skip over
b = 0; //because i initialize it here instead of doing it like the a variable
label1:
//other instructions
as you can see I have two variables initialized but one of them is defined then initialized but the other one is defined and initialized at the same line.
The one that is defined and initialized at the same line variable a does not produce an error when skipped over, but the other one does.
I'm using VS2019 to compile this code. I think this should not throw an error at all and the compiler should give you a warning so that you know you're skipping something in both cases a and b initializations.
Is there any solution to this like disabling something in the settings?
I don't want to declare my variables then initialized them when using labels.
I think this should not throw an error at all
The compiler is free to refuse to compile ill-formed programs.
Is there any solution to this
Solutions:
Don't initialise a.
Declare a before the jump.
Declare a after the label.
Don't use the goto (my favourite).
Limit the scope of a by declaring it within a block statement that ends before the label.
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 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.
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.
I have a .cpp file (let's call it statinit.cpp) compiled and linked into my executable using gcc.
My main() function is not in statinit.cpp.
statinit.cpp has some static initializations that I need running.
However, I never explicitly reference anything from statinit.cpp in my main(), or in anything referenced by it.
What happens (I suppose) is that the linked object created from statinit.cpp is never loaded on runtime, so my static initializations are never run, causing a problem elsewhere in the code (that was very difficult to debug, but I traced it eventually).
Is there a standard library function, linker option, compiler option, or something that can let me force that object to load on runtime without referencing one of its elements?
What I thought to do is to define a dummy function in statinit.cpp, declare it in a header file that main() sees, and call that dummy function from main(). However, this is a very ugly solution and I'd very much like to avoid making changes in statinit.cpp itself.
Thanks,
Daniel
It is not exactly clear what the problem is:
C++ does not have the concept of static initializers.
So one presume you have an object in "File Scope".
If this object is in the global namespace then it will be constructed before main() is called and destroyed after main() exits (assuming it is in the application).
If this object is in a namespace then optionally the implementation can opt to lazy initialize the variable. This just means that it will be fully initialized before first use. So if you are relying on a side affect from construction then put the object in the global namespace.
Now a reason you may not be seeing the constructor to this object execute is that it was not linked into the application. This is a linker issue and not a language issue. This happens when the object is compiled into a static library and your application is then linked against the static library. The linker will only load into the application functions/objects that are explicitly referenced from the application (ie things that resolve undefined things in the symbol table).
To solve this problem you have a couple of options.
Don't use static libraries.
Compile into dynamic libraries (the norm nowadays).
Compile all the source directly into the application.
Make an explicit reference to the object from within main.
I ran into the same problem.
Write a file, DoNotOptimizeAway.cpp:
void NoDeadcodeElimination()
{
// Here use at least once each of the variables that you'll need.
}
Then call NoDeadcodeElimination() from main.
EDIT: alternatively you can edit your linker options and tell it to always link everything, even if it's not used. I don't like this approach though since executables will get much bigger.
These problems, and the problems with these potential solutions all revolve around the fact that you can't guarantee much about static initialization. So since it's not dependable, don't depend on it!
Explicitly initialize data with a static "InititalizeLibrary" type static function. Now you guarantee it happens, and you guarantee when it happens in relation to other code based on when you make the call.
One C++'ish way to do this is with Singletons.
Essentially, write a function to return a reference to the object. To force it to initialize, make it a static object inside the function.
Make a class static function that is vaguely like this:
class MyClass {
static MyClass& getObject()
{
static MyObject obj;
return obj;
}
};
Since you are using C++, you could always declare a global object (ie a global variable that references a class in statinit.cpp. As always, the constructor will be called on initialization and since the object is global, this will be called before main() is run.
There is one very important caveat though. There is no guarantee as to when the constructor will be called and there is no way to explicitly order when each of these constructors is called. This will also probably defeat any attempt to check for memory leaks since you can no longer guarantee that all the memory allocated while running main has been deallocated.
Is the problem that the static items were never initialized, or is the problem that the static items weren't initialized when you needed to use them?
All static initialization is supposed to be finished before your main() runs. However, you can run into issues if you initialize on static object with another static object. (Note: this doesn't apply if you are using primitives such as int)
For example, if you have in file x.cpp:
static myClass x(someVals);
And in y.cpp:
static myClass y = x * 2;
It's possible that the system will try to instantiate y before x is created. In that case, the "y" variable will likely be 0, as x is likely 0 before it is initialized.
In general, the best solution for this is to instantiate the object when it is first used (if possible). However, I noticed above you weren't allowed to modify that file. Are the values from that file being used elsewhere, and maybe you can change how those values are accessed?
Read the manual page for the ld command and look at the -u option. If statinit.cpp defines anything that looks like a function then try naming it in -u. Otherwise choose a data object that's defined in statinit.cpp and name that in -u, and hope it works. I think it's best if you write the command line so the -u option comes immediately before your -l option for your library that has statinit's object code in it.
Of course the dynamic library solution is the best, but I've also been told it's possible to link the whole static library with the linker option:
-Wl,-whole-archive
before the library's -l option, and
-Wl,-no-whole-archive
after it (to avoid including other libraries as a whole, too).