Search code examples
c++multiple-definition-error

C++ Multiple definition of helper function


EDIT: Answered -- the issue was that because the functions had the same signature, despite them being in separate files, C++ saw both versions and got confused.

I have three classes: Table and Bed both inherit from Furniture.

Table and Bed each have a helper function GetLowerCase(std::string) defined in each class individually. When make is run (Makefile shown below), I get an error saying that GetLowerCase in Bed.cpp was first defined in Table.cpp

Makefile:

main: main.o Furniture.o Table.o Bed.o
        g++ main.o Furniture.o Table.o Bed.o -o main

main.o: main.cpp
        g++ -c main.cpp

Furniture.o: Furniture.cpp Furniture.h
        g++ -c Furniture.cpp

Table.o: Furniture.cpp Table.cpp Table.h
        g++ -c Table.cpp

Bed.o: Furniture.cpp Bed.cpp Bed.h
        g++ -c Bed.cpp

clean:
        rm *.o main

Table.cpp:

#include "Table.h"
#include <iostream>
#include <string>

std::string GetLowerCase(std::string str)
{
        std::string out;
        for (int i=0; i<str.length(); i++)
        {
                out[i] = tolower(str[i]);
        }
        return out;
}

Table::Table(const std::string n, std::string wt) : Furniture(n)
{
        wood_type = GetLowerCase(wt);
        if (wood_type != "pine" && wood_type != "oak")
        {
                std::cerr << "Wood type must be OAK or PINE.";
        }
}

void Table::Print()
{
        Furniture::Print();
        std::cout << "Wood Type: " << wood_type << std::endl;
}

Bed.cpp:

#include "Bed.h"
#include <iostream>
#include <string>

std::string GetLowerCase(std::string str)
{
        std::string out;
        for (int i=0; i<str.length(); i++)
        {
                out[i] = tolower(str[i]);
        }
        return out;
}

Bed::Bed(const std::string n, std::string sz) : Furniture(n)
{
        size = GetLowerCase(sz);
        if (size != "twin" && size != "full" && size != "queen" && size != "king")
        {
                std::cerr << "Bed size must be TWIN, FULL, QUEEN, or KING.";
        }
}

void Bed::Print()
{
        Furniture::Print();
        std::cout << "Size: " << size << std::endl;
}

I would have thought that GetLowerCase would be entirely contained within the .cpp file it was defined in and wouldn't be "seen" by any other files.

It's not in any header or source files besides the two listed above. Very confused, and would love some help!


Solution

  • Either declare your function static or wrap it in an anonymous namespace:

    namespace {
        // duplicated names here.
    }