C++ and Catch – Adding your Own Main Method

When you begin coding on a project, it is perfectly acceptable and even advisable to allow the Catch library to generate the main method for you.  That is what the #define CATCH_CONFIG_MAIN (very first line in the tests.cpp file)  directive tells Catch to do.

As you transition from implementing the data structures to implementing a higher-level project, you will want to eventually create your own main method.  Here is how to transition to using your own main without getting rid of tests and testing.

In QtCreator, follow these steps

  1. Add a new cpp file to your project that will contain your main driver.  If you still have the original main.cpp that was added when you created the project, that is fine to use as well; make sure it is listed in the project explorer on the left side of the code window.
  2. Comment out#define CATCH_CONFIG_MAIN at the top of the tests.cpp file.  This will tell the Catch library NOT to generate its own main method.
  3. In your main driver file, copy and paste the following code (to start with). Read the comments throughout to help you understand what is going on.
//CATCH_CONFIG_RUNNER tells the catch library that this 
//project will now explicitly call for the tests to be run. 
#include "catch.hpp"

//A macro used in main to determine if you want to run
//the tests or not. If you don't want to run your tests,
//change true to false in the line below.
#define TEST true

* runCatchTests will cause Catch to go ahead and
* run your tests (that are contained in the tests.cpp file.
* to do that, it needs access to the command line
* args - argc and argv. It returns an integer that
* ultimately gets passed back up to the operating system.
* See the if statement at the top of main for
* a better overview.
int runCatchTests(int argc, char* const argv[])
    //This line of code causes the Catch library to 
    //run the tests in the project. 
    return Catch::Session().run(argc, argv);

int main( int argc, char* const argv[] )
    //If the TEST macro is defined to be true,
    //runCatchTests will be called and immediately
    //return causing the program to terminate. Change TEST
    //to false in the macro def at the top of this file
    //to skip tests and run the rest of your code.
    if (TEST)
        return runCatchTests(argc, argv);

    //start working on other parts of your project here.
    return 0;

Once you’ve added that code, rebuild your project (Build menu| Rebuild All) then execute your project.  Your tests should run as normal.

Speak Your Mind



This site uses Akismet to reduce spam. Learn how your comment data is processed.