2

In C or C++ if I have a program with the following structure:

..includes..
..defines..

void function_one(int i) {
    ...
}

void function_two(const char * str) {
    ...
}

int main(int argc, char *argv[]) {
    ...
}

Saved as main.c/cpp.

How can I write a new file test.c/cpp where I can make calls to the functions in the main.c/cpp?

How am I am doing it now:

Compiler flag: -etest_main
Files to compile: main.c test.c
Running test output: Blank no errors

My test main prints "here" but im not sure why the test executable isnt.

harpun
  • 4,022
  • 1
  • 36
  • 40
user2843645
  • 45
  • 1
  • 8
  • You might like to add a few more details to the code snippet, e.g. where's the line that would print "here" – Rob Wells Oct 11 '13 at 18:20

2 Answers2

5

Take a look at CUnit so you don't have to reinvent the wheel. And here's their Intro for Devs doc.

It's a part of the xUnit series of test frameworks and has been around for years.

Rob Wells
  • 36,220
  • 13
  • 81
  • 146
0

You can't easily test functions which reside in the same compile unit as the main function.

Possible solutions:

Split your main.{c/cpp} into two source files (compile units). One file shall only contain the main function, the other file all other functions. When doing unit tests, just don't link in the compile unit containing the single main function.

Alternatively, use macros to exclude the main function when compiling for unit tests.

villekulla
  • 1,039
  • 5
  • 15
  • 1
    Or use the loader's entry point option to start at some entry other than "main". That makes "main" just another function. – mpez0 Oct 11 '13 at 19:17
  • @mpez0 See http://stackoverflow.com/a/3379260/2824853 that this may introduce other problems... – villekulla Oct 11 '13 at 19:26