I have code
#include <stdlib.h>
void *gg = malloc(55);
int main(int argc, char **argv)
{
return 0;
}
gcc fail to compile but g++ works.
So, I just want to make sure that the malloc calling happens before main is exectued.
What you do is allowed in C++. The C++ standard has a whole section on "Dynamic initialization of non-local variables".
Looking at the assembly generated by GCC for your code is instructive:
Here the initializers are called through two generated functions, _GLOBAL__sub_I_gg (which is called before main) which in turn calls __static_initialization_and_destruction_0.
It is within the body of the latter function you will find the call to malloc.
Related
I have a C program that I need to interface with a C++ library (ROS). Normally, it's not too difficult to interface C code with C++ code with a wrapper using extern "C" and using the C++ compiler to link, but I've never had to do it where main was in the C portion.
The C++ FAQ indicates that this is a bad thing:
Here are some high points (though some compiler-vendors might not require all these; check with your compiler-vendor’s documentation):
You must use your C++ compiler when compiling main() (e.g., for static initialization)
But I see another source saying it should be okay these days:
At one time, most C++ compilers required that function main be compiled by the C++ compiler. That requirement is not common today, ...
Why would it matter whether main is in the C portion or the C++ portion? How much trouble would I be in if I try to link code where it's in the C portion using common linkers today (mainly GCC's and Clang's)?
One easy way to work around this is to rename your C main() and call it from a new C++ main()
As in:
// in ypur current C main module
int my_c_main(int argc, char* argv[]) /* renamed, was main() */
{
/* ... */
]
// in a c++ module...
int main(int argc, char* argv[])
{
extern "C" int my_c_main(int argc, char* argv[]);
// if your c main() requires environment variables passed in envp,
// You can allocate space for strings and an array here and pass
// the environment variables you'll need, as the third parameter
// to my_c_main(), or pass environ, if your system has
// it defined in unistd.h
return my_c_main(argc, argv);
}
I'm just learning c++. I have a main.cpp unit which has a lot of stuff in it already, and I just want to build a quick little testMain.cpp unit that will test a couple of things.
Basically I want to trick the compiler (xCode) into ignoring the real main function for a minute. I could
Rename the main() function inside main.cpp to mmain() temporarily.
Remove the reference to main.cpp in my project temporarily.
Comment out the main() method in main.cpp temporarily.
All these seem pretty clunky. There has to be an easier way. I suspect this is a common thing people do. How do you do it?
Another solution would be to separate the code into multiple files, have most of the logic in one file, have the real main in another and the test main in a third, you compile and link either the first and second or first and third files but never all three together.
Your option 2 is the most common strategie, and from my understanding also the cleanest.
After all, your test application will most likely not share the same command line interface, and that is usually about the only thing which should (of at all) be located in the main function or file.
If your main.cpp contains significantly more than just the entry point, you should immediately start thinking about how to distribute that logic into the modules you already have.
Use a macro.
Option 1: Use a macro to include/exclude entire files:
main.cpp:
#ifdef USE_REAL_MAIN
int main(int argc, char* argv[]) {
...
}
#endif
testMain.cpp
#ifdef USE_TEST_MAIN
int main(int argc, char* argv[]) {
...
}
#ENDIF
build file:
gcc -DUSE_REAL_MAIN
gcc -DUSE_TEST_MAIN
Option 2: Use a command-line macro to rename main:
main.cpp:
int realMain(int argc, char* argv[]) {
...
}
testMain.cpp
int testMain(int argc, char* argv[]) {
...
}
build file:
gcc -DrealMain=main
gcc -DtestMain=main
Note this is probably the least attractive option because it breaks the convention of macros having UPPER_CASE names and means the real entrypoint of your program is non-obvious to someone who hasn't seen the build script. It also means the program simply won't compile (as there's no main function) without your custom build script either.
Option 3: Have a new common main with the #ifdef directives instead:
main.cpp
#include "realMain.h"
#include "testMain.h"
int main(int argc, char* argv[]) {
#ifdef USE_TEST_MAIN
return testMain( argc, argv );
#else
return realMain( argc, argv );
#endif
}
build file:
gcc -DUSE_REAL_MAIN
gcc -DUSE_TEST_MAIN
I think this is my preferred option because it's almost self-documenting and makes it clear to another programmer how to get it to work without needing your custom build script.
WinMain is a function that 'replaces' the default main entry point 'main'.
The user can then define its main entry point like
int WINAPI WinMain(...) { }
How is this kind of encapsulation done?
Well, most likely, at some point it looks like this:
int main() // This must be defined somewhere in windows.h
{
return WinMain(...);
}
Question: How can I accomplish such an encapsulation of my own, which then calls WinMain? Note: The library which I made is a DLL, so it will look like this:
// This is the minimal code for the application which uses 'MyLibrary'
#pragma comment(lib, "MyLibrary.lib")
include "MyLibrary.h"
void Main(MyCustomParameter *params)
{
// Write user code here
}
The problem however is, that the DLL doesn't 'know' the Main() function and therefore throws an 'unresolved external symbol' compile error. So how can I encapsulate it like this?
You have to decide on a signature of your custom main function and declare it as "extern" (extern "C" in case of C++). Then, application code will have to define that function and link against your static library that has the actual _main entry point. For example:
extern "C" int my_main(int argc, char *argv[]);
int main(int argc, char *argv[])
{
return my_main(argc, argv);
}
Actually, the real entry point is neither main nor WinMain. The real entry point is one of wWinMainCRTStartup, WinMainCRTStartup, wmainCRTStartup, and mainCRTStartup. But they're not defined in Windows.h, they're part of the CRT. You can see their code in <VS installation folder>\VC\crt\src\crtexe.c. They each do some initialization and then call one of wWinMain, WinMain, wmain, and main, respectively.
As mentioned by someone else you can override the entry point with the /ENTRY switch, but you still can't have custom parameters, which is the whole reason you want to do this in the first place.
The linker default entry point name is "main".
You can override the default to start with any function you want.
/ENTRY (Entry-Point Symbol)
In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following:
class Init {
public:
Init() { initialize(); }
};
Init init;
Ideally I'd like to be able to simply write:
initialize();
but this doesn't compile...
Is there a less verbose way to achieve the same effect?
Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code).
Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.
You can use GCC's constructor attribute to ensure that it gets called before main():
void Init(void) __attribute__((constructor));
void Init(void) { /* code */ } // This will always run before main()
You can make the above very slightly shorter by giving "initialize" a return type, and using that to initialize a global variable:
int initialize();
int dummy = initialize();
However, you need to be careful with this, the standard does not guarantee that the above initialization (or the one for your init object) takes place before main is run (3.6.2/3):
It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main.
The only thing that is guaranteed is that the initialization will take place before 'dummy' is ever used.
A more intrusive option (if it's possible) might be to use "-D main=avr_main" in your makefile. You could then add your own main as follows:
// Add a declaration for the main declared by the avr compiler.
int avr_main (int argc, const char * argv[]); // Needs to match exactly
#undef main
int main (int argc, const char * argv[])
{
initialize ();
return avr_main (argc, argv);
}
At least here you're guaranteed that the initialization will take place when you expect.
Here's a somewhat evil method of achieving this:
#include <stdio.h>
static int bar = 0;
int __real_main(int argc, char **argv);
int __wrap_main(int argc, char **argv)
{
bar = 1;
return __real_main(argc, argv);
}
int main(int argc, char **argv)
{
printf("bar %d\n",bar);
return 0;
}
Add the following to the linker flags: --wrap main
eg.
gcc -Xlinker --wrap -Xlinker main a.c
The linker will replace all calls to main with calls to __wrap_main, see the ld man page on --wrap
Your solution in simple and clean. What you can additionally do is to put your code in anonymous namespace. I don't see any need to make it better than that :)
If you are using the Arduino environment, is there any reason you can't place it in the setup method?
Of course, this is after the Arduino-specific hardware setup, so if you have such low-level stuff that it really has to go before main, then you need some constructor magic.
UPDATE:
Ok, if it has to be done before the main I think the only way is to use a constructor like you already do.
You can always make a preprocessor macro of it:
#define RUN_EARLY(code) \
namespace { \
class Init { \
Init() { code; } \
}; \
Init init; \
}
Now this should work:
RUN_EARLY(initialize())
But it's not really making things shorter, just moving the verbose code around.
You can use the ".init*" sections to add C code to be run before main() (and even the C runtime). These sections are linked into the executable at the end and called up at specific time during program initialization. You can get the list here:
http://www.nongnu.org/avr-libc/user-manual/mem_sections.html
.init1 for example is weakly bound to __init(), so if you define __init(), it will be linked and called first thing. However, the stack hasn't been setup, so you have to be careful in what you do (only use register8_t variable, not call any functions).
Use static members of classes. They are initialized before entering to main. The disadvantage is that you can't control the order of the initialization of the static class members.
Here is your example transformed:
class Init {
private:
// Made the constructor private, so to avoid calling it in other situation
// than for the initialization of the static member.
Init() { initialize(); }
private:
static Init INIT;
};
Init Init::INIT;
Sure, you put this in one of your your header files, say preinit.h:
class Init { public: Init() { initialize(); } }; Init init;
and then, in one of your compilation units, put:
void initialize(void) {
// weave your magic here.
}
#include "preinit.h"
I know that's a kludge but I'm not aware of any portable way to do pre-main initialization without using a class constructor executed at file scope.
You should also be careful of including more than one of these initialization functions since I don't believe C++ dictates the order - it could be random.
I'm not sure of this "sketch" of which you speak but would it be possible to transform the main compilation unit with a script before having it passed to the compiler, something like:
awk '{print;if (substr($0,0,11) == "int main (") {print "initialize();"};}'
You can see how this would affect your program because:
echo '#include <stdio.h>
int main (void) {
int x = 1;
return 0;
}' | awk '{
print;
if (substr($0,0,11) == "int main (") {
print " initialize();"
}
}'
generates the following with the initialize() call added:
#include <stdio.h>
int main (void) {
initialize();
int x = 1;
return 0;
}
It may be that you can't post-process the generated file in which case you should ignore that final option, but that's what I'd be looking at first.
There is how I perform pre-main coding.
There are sever init sections executed before main, refers to http://www.nongnu.org/avr-libc/user-manual/mem_sections.html initN sections.
Anyhow, this only works on -O0 optimization for some reason. I still try to find out which option "optimized" my pre-main assembly code away.
static void
__attribute__ ((naked))
__attribute__ ((section (".init8"))) /* run this right before main */
__attribute__ ((unused)) /* Kill the unused function warning */
stack_init(void) {assembly stuff}
Update, it turns out I claimed this function is unused, leading to optimize the routine away. I was intended to kill function unused warning. It is fixed to used used attribute instead.
In Visual Studio 2003 using pure C, old-style function
declarations do not show as global member
i.e. void func(blah) int blah;{...}
This shows as a global member in the members dropdown:
void func(int blah)
{
...
}
This compiles, but old-style does not appear in the global
members dropdown:
void func(blah)
int blah;
{
...
}
I am trying to use the new 'Calling Graph' functionality to
analyse code, but as most of our legacy code uses the
old-style function parameters, those functions are not
recognized are not shown as Global Members, and therefore do
not appear in the 'Calling Graph'.
Is there any way to let the "call graph" analysis process
old-style function declarations correctly?
Maybe you want to consider to just change the old style function signatures. There shouldn't be any issues with that.
EDIT:
For an automatic conversion of your source files from old style syntax to ANSI-C style, take a look at the cproto tool. Maybe that could save you some time if you decide to go that direction.
This is an excerpt from the docs:
-f n
Set the style of generated function prototypes where n is a
number from 0 to 3. For example,
consider the function definition
main (argc, argv)
int argc;
char *argv[];
{
}
If the value is 0, then no prototypes are generated. When set to
1, the output is:
int main(/*int argc, char *argv[]*/);
For a value of 2, the output has the form:
int main(int /*argc*/, char */*argv*/[]);
The default value is 3. It produces the full function prototype:
int main(int argc, char *argv[]);
I'm not sure but maybe the engine uses regexs to trace routine signatures and the old C style isn't implemented.