1

My problem is that I have header-file (custom unit-test framework) with function definitions in it. For example:
unit_test.h:

#pragma once
...    
void Assert(bool b, const string& hint = {})
{
    AssertEqual(b, true, hint);
}
...

it's convenient for me to keep some functions defined right in the header, because I often use this functional by simply including (unit_test.h is located in separate directory C:/Dev/include).
But if I am dealing with a project where multiple cpp files use this functionality, I get a multiple definition error as expected.
Simple project looks like:

main.cpp:

#include "unit_test.h"

void foo();

int main()
{
    Assert(1);
    foo();
    return 0;
}

foo.cpp:

#include "unit_test.h"

void foo()
{
    Assert(2);
}

So I want to know if there is a right way to keep function definitions in a header file and use it in project without getting an multiple definition error?
(Or would it be better to move the function definitions to the source and compile it separately each time, or compile unit_test into a static library?)

3 Answers3

1

Easiest way to achieve it, is to add inline keyword in function definiton, but it's not a best solution.

Best option is to move definition to source file, but only it it's not a template.

1

I would use anonymous namespace with inline:

namespace {
    inline void Assert(bool b, const string& hint = {})
    {
        AssertEqual(b, true, hint);
    }
}
Nikola
  • 125
  • 1
  • 8
0

This error is beacuse whenever you will include the file it will define the function again. The solution is make a header file unit_test.h with declaration only and create a source file unit_test.cpp for definition. Now you can include header file it will not give error. Don't forget to add #ifndef in header as follow

unit_test.h

#ifndef UNIT_TEST_H_
#define UNIT_TEST_H_
// Declare you function
// and end with:
#endif
Imran
  • 775
  • 7
  • 19