user2843645
user2843645

Reputation: 45

C unit testing functions

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.

Upvotes: 2

Views: 2849

Answers (2)

Rob Wells
Rob Wells

Reputation: 37103

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.

Upvotes: 5

villekulla
villekulla

Reputation: 1085

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.

Upvotes: 0

Related Questions