Sign in to follow this  
rdansie

C++ Multiple source files

Recommended Posts

Ive been working on a program for a while and now im splitting my classes into seperate files. I havent used multiple source files before so im basically just guessing. What i did was create a new cpp file copied and pasted a class into it. Then at the top of the original source file i put: #include "newfile.cpp" When i try to compile it says that i have already defined the class even though i cut it from from the original file. When i create a completely new class in the new file it works fine for me. I modified both files to make sure that they were both recompiled. The compiler im using is visual c++. Thanks for any help you can offer

Share this post


Link to post
Share on other sites
Your classes should consist of two files: ClassName.h and ClassName.cpp. The class definition should be in the header file while the body of the class is in the .cpp file. In every header file you ever make, make sure to include this code...


#ifndef CLASSNAME_H
#define CLASSNAME_H

class ClassName
{
// members and methods here
};

#endif



Basically makes it so that a header file is only called once. Hope that helps.

Share this post


Link to post
Share on other sites
Quote:
Original post by rdansie
Ive been working on a program for a while and now im splitting my classes into seperate files. I havent used multiple source files before so im basically just guessing. What i did was create a new cpp file copied and pasted a class into it. Then at the top of the original source file i put:
#include "newfile.cpp"

When i try to compile it says that i have already defined the class even though i cut it from from the original file. When i create a completely new class in the new file it works fine for me. I modified both files to make sure that they were both recompiled. The compiler im using is visual c++. Thanks for any help you can offer


What you do is this:

// FILE.h
// Safe-guards:
#ifndef FILE_H
#define FILE_H

class MyClass {
public:
void SomeFunc();
};

#endif

// FILE.cpp
#include "File.h"

void MyClass::SomeFunc() {
return;
}

// OTHER_FILE.cpp
#include "File.h"

MyClass my_instance;

int main() {
my_instance.SomeFunc();
}


You DECLARE the class in the .h, IMPLEMENT it in the .cpp, and use the .h for everywhere where it is needed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this