How to have multiple .cpp files in my program

http://i39.tinypic.com/314f5z9.png

That is the picture, I would want that code in a different file and then some way to get in the main file and use it. Beacuse there would be too messy and I couldn't code if it was all in main.cpp

Than-... I didn't even say hi, how rude of me...

Hi everyone, and thanks in advance!

tarik00555
Hi tarik!

One way would be to just create a blank text file with a *.cpp extension, and from the project menu in Code::Blocks just do the 'Add File' thing. I right click on the Project Explorer and choose the menu option to add an existing file.

Another alternative is to use the Project Explorer functionality to add a blank file to the project, then give it a cpp extension. Same goes with header files.

Fred
just include the second cpp source file eg if its in the same directory
#include "cppfile2.cpp"
otherwise something like
#include "\cppfile2.cpp"
where ever the directory is
Last edited on
Thank you giblit!
Not much is visible on the "pic" you posted, BUT, the solutions posted by the other contributors here "should" work!!
I have to disagree with giblit. While the included "header files" can be named freely, the convention is that a *.cpp does contain implementation for a corresponding, separate compilation unit.

Compiling a program has two stages. First, compiler generates an object file for each compilation unit. Second, a linker forms the executable binary from the object files and necessary libraries.

A programming environment (IDE) has concept "project". If you have somehow managed to add one unit named "main.cpp", then surely the thingy has a method to add more files. If added properly, the IDE should also include them for compilation and linking.

Lets look at a simple program:
1
2
3
4
#include <iostream>
void main() {
  std::cout << "Hello Dolly!\n";
}

It does refer to a global object std::cout and calls function operator<<. Both are implemented in some other compilation unit (within a library). The header file "iostream" declares those two. Those declarations are needed by the compiler to ensure that the linking will have in the main's object file calls that match symbols within library.

Having a header file is not necessary, but then you have to write the correct declarations to every *.cpp that needs them.

So.
1
2
3
4
5
6
// menu.h
#ifndef MENU_H
#define MENU_H
#include <whatever declares WINDOW>
void print_menu( WINDOW *, int );
#endif 

1
2
3
4
5
6
7
// menu.cpp
#include <other necessary headers>
#include "menu.h"
void print_menu( WINDOW * menu, int high )
{
  // the code
}

1
2
3
4
5
6
7
8
// main.cpp
#include <other necessary headers>
#include "menu.h"

int main()
{
  // the code
}
Topic archived. No new replies allowed.