0

I have a file with all my logic, and I would like to write a separate file to test the functions in my main file.

How do I go about doing this? Should I make it a header file? Could I do something like

#include mainfile.cpp

If they're in the same directory?

Shisui
  • 1,051
  • 1
  • 8
  • 23
  • 1
    If you ever write `#include` of a .c or a .cpp file then something has gone horribly wrong. cpp files should include header files, not the other way around. You should absolutely write a header, but the inclusion happens the opposite way than what you said – Silvio Mayolo Mar 11 '22 at 04:23
  • 1
    Are you using an IDE? Most C++ IDEs [come with built-in support for unit-testing](https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2022), so I'd recommend using that instead of trying to roll-your-own. – Dai Mar 11 '22 at 04:24
  • @SilvioMayolo what do you mean by opposite way? – Shisui Mar 11 '22 at 04:24
  • 2
    @SilvioMayolo Normally a header for a `.cpp` file won't include the names of free-functions and types the author kept "private" to the source-file though. – Dai Mar 11 '22 at 04:25
  • 1
    Also: https://hackingcpp.com/cpp/tools/testing_frameworks.html – Dai Mar 11 '22 at 04:25
  • 2
    If you have a `mainfile.cpp`, you should write a `mainfile.h` and the top of your `mainfile.cpp` (and any other file where you want to use `mainfile`) should say `#include "mainfile.h"`. The cpp file should include the header. – Silvio Mayolo Mar 11 '22 at 04:25
  • this explained why you shouldn't do the way https://stackoverflow.com/questions/1686204/why-should-i-not-include-cpp-files-and-instead-use-a-header. lets link mainfile.cpp with seperated test file – long.kl Mar 11 '22 at 04:58
  • 1
    @long.kl This is about writing tests, so that question is in no way relevant. – hyde Mar 11 '22 at 06:23
  • 1
    @SilvioMayolo This question is about testing. The tests may need access to stuff, which is not exposed in any header. Further, `mainfile.cpp` (assuming it is the file with `main` function) shouldn't even have a `mainfile.h`, because that will create a mess of circular includes. If you ever need to have `mainfile.h`, you should move all that stuff into `somefile.cpp` and create `somefile.h` for that stuff, instead. – hyde Mar 11 '22 at 06:25
  • This question seems to be "how do I write tests for a C++ application", and that's awfully broad, and as such not quite suitable for Stack Overflow. There are a multitude of test utilities and frameworks for C++, which do things in different ways. They are generally easy to add to your project, and have decent examples/introduction/tutorial, so you can check out several different ones. – hyde Mar 11 '22 at 06:30

0 Answers0