Pablo Arias
Pablo Arias

Reputation: 380

Multiple definition of class

I'm writing utility functions for my current project.

Right now, I have a utility.h header which defines a class with static methods:

#pragma once

class Utils
{
public:
    static int firstFunc()
    {
       return 0;
    }

    static bool secondFunc()
    {
      return false;
    }
};

This header is included every time I need to use such functions (in two translation units at the moment) and it works just fine.

Now, after a code review, it was suggested to replace this class by C-style functions. My naive first attempt:

#pragma once

int firstFunc()
{
    return 0;
}

bool secondFunc()
{
    return false;
}

failed to link, returning a multiple definition of function error. I understand why this happens: the header utils.h, which contains the function definitions, is present in two different compilation units: the linker doesn't know which definition to use.

I know that the solution is to move the definitions to a dedicated utils.cpp and leave only the declarations in the header.

My question now is: why didn't this happen when I had the class with static methods, when I still had multiple definitions of the same class in different translation units?

Upvotes: 5

Views: 1728

Answers (1)

Quentin
Quentin

Reputation: 63124

Functions definitions (static or not) that are written directly inside the class body are implicitly inline. Had you separated the definitions:

#pragma once

class Utils
{
public:
    static int firstFunc();

    static bool secondFunc();
};

static int Utils::firstFunc()
{
   return 0;
}

static bool Utils::secondFunc()
{
  return false;
}

... you'd have witnessed the exact same multiple definition error.

Also, these are not "C-style functions", just free (non-member) functions. C++ has nothing against free functions ;)

Upvotes: 3

Related Questions