# 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 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_Hclass ClassName{  // members and methods here};#endif

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

##### Share on other sites
Quote:
 Original post by rdansieIve 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_Hclass 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.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627749
• Total Posts
2978913

• 10
• 10
• 21
• 14
• 14