kalenpw kalenpw - 2 months ago 7
C++ Question

C++ class in separate file not compiling. Already defined in Class.obj one or more multiply defined symbols found

So I've done extensive googling and searching on StackOverflow and am unable to find a solution despite several answers with this exact issue.

I am trying to create a test class in an external file called

Fpc5.cpp


It's contents are:

Fpc5.cpp


#include "stdafx.h"
#include "Fpc5.h";
#include <iostream>
using std::cout;

class Fpc5 {
int bar;
public:
void testMethod();
};

void Fpc5::testMethod() {
cout << "Hey it worked! ";
}


and my main .cpp file:

Test.cpp


// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
//#include "Fpc5.cpp"
#include "Fpc5.h";
using std::cout;
using std::cin;
using std::endl;

int main()
{
cout << "Hello" << endl;
Fpc5 testObj;
testObj.testMethod();

system("pause");
return 0;
}


all the answers I've read indicate this is caused becaused I used to be including the class in the main file itself which is why I created a header file

Fpc5.h


#pragma once
void testMethod();


This changed the error, but still did not fix the issue. Currently my
Test.cpp
does not recognize a Fpc5 class. I've also tried adding the
Fpc5.cpp
and
Fpc5.h
in
stdafx.h
and that still does not resolve the issue.

stdafx.h


// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

//#include "Fpc5.cpp"
#include "Fpc5.h"


I'm sure this a simple syntax/conceptual understanding error, but I'm quite new to c++ and am not sure what is wrong.

Answer

This is definition of your class and it must be in Fpc5.h

class Fpc5 {
    int bar;
public:
    void testMethod();
};

Then, you have Fpc5.cpp where you implement methods of the class:

#include "Fpc5.h" // Compiler needs class definition to compile this file!

void Fpc5::testMethod()
{
}

And then you can use Fpc5 class in Test.cpp

#include "Fpc5.h"

int main()
{
    Fpc5 foo;
    foo.testMethod();
    return 0;
}

As an alternative you can pack everything into Test.cpp

Comments