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.

1
  • You might like to add a few more details to the code snippet, e.g. where's the line that would print "here" Commented Oct 11, 2013 at 18:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How would that solve the questioners problem having functions to be unit tested next to the main function?
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.

2 Comments

Or use the loader's entry point option to start at some entry other than "main". That makes "main" just another function.
@mpez0 See stackoverflow.com/a/3379260/2824853 that this may introduce other problems...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.