(C++) How to link .cpp files

Hey folks,

Sorry if this is a stupid question, I’m fairly new to C++.

Within my project file, in a fork of DaisyExamples, here’s a simplified representation of my source files:

Jellybeans.cpp

#include "theory.h"

using namespace jellybeans;

int main(void) {
    // Initialize hardware
    patch.Init();
    int test = ccc("1");
}

theory.h

namespace jellybeans {
    int ccc(std::string);
}

theory.cpp

#include "theory.h"

using namespace jellybeans;

int ccc(std::string div){
    return 1;
}

Makefile

# Project Name
TARGET = Jellybeans

# Sources
CPP_SOURCES = Jellybeans.cpp \
theory.cpp

# Library Locations
LIBDAISY_DIR = ../../libdaisy
DAISYSP_DIR = ../../DaisySP

# Core location, and generic Makefile.
SYSTEM_FILES_DIR = $(LIBDAISY_DIR)/core
include $(SYSTEM_FILES_DIR)/Makefile

When I try to compile this, I get a linker error saying that Jellybeans.cpp is making an undefined reference to ccc(). To my understanding, this is occurring because Jellybeans.cpp and theory.cpp need to be linked together into one object file. Problem is, the core Makefile in libDaisy compiles each .cpp file as a separate object file:

libDaisy/core/Makefile

OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(CPP_SOURCES:.cpp=.o)))
vpath %.cpp $(sort $(dir $(CPP_SOURCES)))

If possible, I’d prefer a solution that didn’t require overriding the core Makefile. How would you recommend that I implement this?

Thanks :slight_smile:

Nope, they don’t get linked into one object files. They get compiled into separate object files and then those objects files are linked together in a single executable with your patch.

The problem here is that your ccc function implementation is not in jellybeans namespace. And the function declaration that is visible from theory.h becomes undefined. So theory.cpp should look like that work as intended:

#include "theory.h"

namespace jellybeans {
    int ccc(std::string div){
        return 1;
    }
}

Welcome to the wonderful world of C++ :wink:

2 Likes

Sure enough, that fixed the bug. Thank you so much for your expertise!

2 Likes