11

How do I define my own main() function when testing with boost?

Boost is using it's own main function, but I'm using a custom memory manager and it needs to be initialized before any memory is allocated, otherwise I'll get errors.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
NomenNescio
  • 2,899
  • 8
  • 44
  • 82

4 Answers4

14

I do not believe you actually need your own main. I think you are much better off with global fixture:

struct AllocatorSetup {
    AllocatorSetup()   { /* setup your allocator here */ }
    ~AllocatorSetup()  { /* shutdown your allocator/check memory leaks here */ }
};

BOOST_GLOBAL_FIXTURE( AllocatorSetup );
Gennadiy Rozental
  • 1,905
  • 2
  • 13
  • 17
8

You have to define

BOOST_TEST_NO_MAIN

before the boost includes.

BOOST_TEST_MAIN

is the default. http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/utf/compilation.html

NomenNescio
  • 2,899
  • 8
  • 44
  • 82
0

You can define a static object and his constructor will execute before main:

class Alloc_Setup {
   Alloc_Setup() {
       // Your init code
   }
   ~Alloc_Setup() {
       // Your cleanup
   }
};
Alloc_Setup setup;
int main() {} // (generated by boost)
Galimov Albert
  • 7,269
  • 1
  • 24
  • 50
  • 1
    That's more of a hack than a solution, plus it doesn't allow you to define your own main function. No problem tough, I found the answer. – NomenNescio Sep 21 '12 at 18:14
-1

Memory can be allocated before main:

static int* x = new int(1);
int main() { return *x; }

And you could make your memory manager a global variable as well,
but you can't enforce a specific order of global variables initialization. (in standard C++ at least)

In Windows you could put your memory manager into a DLL, at it will be initialized before application entry point will be called, but still, something other may allocate a memory before - another DLL, or CRT of your DLL.

Abyx
  • 12,345
  • 5
  • 44
  • 76
  • 1
    The initialization order of globals is well defined inside a single compilation unit - so you _can_ enforce any order you want. Just place them in a single CU :) – Fiktik Sep 21 '12 at 17:50