Call .cpp files from a .cpp file

Can you call another .cpp file be called in another .cpp file

I want to choose Single player or Multiplayer but not have a crap ton of code between the if else if else. Or is there a better way to go about doing this?


(sorry if the code is sloppy, its just to show you what I would like to do.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  cout << "how many players are there? (1/2)" << endl;
cin >> gamemode;

if (gamemode = 1)
{
//call singleplayer.cpp
}
else if (gamemode = 2)
{
// call multiplayer.cpp
}
else
{
cout << "Not a Valid Answer!"
}
You don't "call" a source file. You call a function in a source file.

Why not make a Player class for which you can have one or two instances?

Lines 4, 8: You're using the assignment operator (=), not the equality operator (==).

Lines 4, 8: You're using the assignment operator (=), not the equality operator (==).

A handy coding style convention is to write constants to the left side:
1
2
3
4
5
6
if ( 1 == gamemode )
{
  //call singleplayer.cpp
}
else if ( 2 == gamemode )
{

Any assignments due to typo is a then a syntax error.

Luckily, at least some compilers do warn about "suspicious assignments". It is good to read what the compiler tells.


Multiple files. For example:
http://www.go4expert.com/articles/write-multi-files-program-cpp-t29978/
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044842972&id=1043284392


You are actually already "calling code that is in another .cpp". Another example:
1
2
3
4
5
6
#include <iostream>

int main() {
  std::cout << "Hello world\n";
  return 0;
}

The std::cout is a variable that is neither declared nor implemented within this file.
The << is a function that is likewise "in some other .cpp".
Both are declared in the header file names "iostream". By including the "iostream" in our .cpp we know the names and types of those objects/functions and can then use them.
You could code the multiplayer and singleplayer differently. then make the launcher cpp. build all of them, then run the launcher.exe which open multiplayer or singleplayer and then closing the launcher program

Like this:

1
2
3
4
5
int gamemode=0;
cin>>gamemode;
if (gamemode==1){
system("singleplayer.exe");
}
Topic archived. No new replies allowed.