-5

i am working with visual studio 2010. i use following code in some cpp files to run a function hundred times before the main function execute.

const int x = some_init_function()

but I found with visual studio, not every global x in init. i want to ask if vc has limitation on this construct?

note: in some_init_function is some code doing things such as registering. And the variable name is different in every cpp file.

1 Answers1

1

If you want to guarantee that the code will run before main(), you need to make your variable static and put it in the same file as main(). Otherwise it may not be initialized before main(). For more on that, see here: Is the static initialization of global variables completed before `main()`?

Alternatively, you can set up a "call before main" function in MSVC using a technique described here: https://stackoverflow.com/a/2390626/4323

If you were using GCC, this would be done using __attribute__((__constructor__)).

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • thank you. i tried static before but does not work. it it difficult to let all the code in the same file as main() :( – rechardchen Dec 18 '15 at 02:38
  • You don't have to put the *code* into the same file as main(), only the *call*. As in, you say `static const int x = foo();` in the same file as main, but you define `foo()` in another file. – John Zwinck Dec 18 '15 at 02:39
  • to me this is the same :( – rechardchen Dec 18 '15 at 02:49
  • @rechardchen: OK then do what is shown in the link I gave you: http://stackoverflow.com/questions/1113409/attribute-constructor-equivalent-in-vc/2390626#2390626 - namely `__declspec(allocate(".CRT$XCU"))`. You can try this in the separate file and see if it works. – John Zwinck Dec 18 '15 at 03:00