Mickaël Perrier Mickaël Perrier - 24 days ago 5
C++ Question

How to pass a value from main.c to another .c file in C++?

I need to pass the value associated to "string OS" from main.cpp, to the "Gameplay.cpp" file in which I use a function/method from "Methods.cpp".

I have five different files:


  • main.cpp

  • Methods.cpp

  • Methods.hpp

  • Gameplay.cpp

  • Gameplay.hpp



In main.cpp :

#include <iostream>
#include <string>
#include "Methods.hpp"
#include "Gameplay.hpp"

using namespace std;

int main()
{
string OS("Windows");

cout << endl << "Are you running on Windows, Mac, or Linux? ";
cin >> OS;

clean(OS);

fight(attaquer, defender);
}


In Methods.cpp :

#include <iostream>
#include <string>
#include "Methods.hpp"

using namespace std;

// Method //
void clean(string OS)
{
if (OS == "Mac" || OS == "Linux")
{
system("clear");
}
else
{
system("cls");
}
}


And, in Gameplay.cpp :

#include <iostream>
#include <string>
#include "main.cpp"
#include "Methods.hpp"
#include "Gameplay.hpp"

using namespace std;

// Method //
void fight(Character attaquer, Character defender)
{
extern string OS;
clean(OS);
// Some code here...
}


Please note that "Character" is a class defined in another file.

The problem is that when I compile this code in Xcode, it fails and return:

Undefined symbols for architecture x86_64:
"_OS", referenced from:
fight(Character, Character) in Gameplay.o


How can I successfully pass this value?

Answer

The string OS variable is local to the main() function, so its name is not a public, globally available symbol. That's why it is inaccessible in other modules. To make it global, define it outside the main().