Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing values between 2 different c++ files in same project

Tags:

c++

noob question right here. How do you pass values between 2 different cpp files in the same project? Do you make objects? if yes, how does the other cpp file see it? some enlightment pls..

EDIT: some clarifications. I'm trying to interface direct input with a program (of which I have the plugins sdk). I'm trying to interface a joystick with it. It seems that there is no main function when I look through the code, but I might be wrong (like, I might not look in the right files). I know programming, and pointers and stuff, classes. Is there anything I should learn or get into in order to achieve what I want?

like image 509
jello Avatar asked Jan 23 '23 08:01

jello


2 Answers

In all but few cases it's a bad idea to share data among compilation units. A compilation unit, just to get you up to speed with the C++ terminology, usually effectively refers to an implementation file (with extension .cpp, or .cc etc.). The way we have the various compilation units "communicate" with each other is with header files and functions, rather than raw data.

Suppose we have an implementation file main.cc and a second implementation file human.cc. We want main.cc to communicate with human.cc. Here we go:

// main.cc
#include "human.hh"
int main()
{
    make_the_human_dance(60);
    return 0;
}


// human.hh
void make_the_human_dance(int duration);


// human.cc
#include "human.hh"
void make_the_human_dance(int duration)
{
    // define how a human dances properly
    // ...
}

Under the same principle you can use classes for communication. Declare the class in the header file and define the class' methods in the implementation file. Sometimes you must provide the implementation of functions in the header files, but that is already going offtopic.

like image 70
wilhelmtell Avatar answered Jan 26 '23 01:01

wilhelmtell


You could declare a global variable in a header file like so:

extern int GlobalVar;

And in exactly one compilation-unit (cpp-file) you have to initialize it:

int GlobalVar = 5;

Any other compilation unit that includes the header now shares the same instance of the global variable (I hope that syntax is correct, i rarely use it).

One should mention, that your question indicates a general lack of understanding of how programs in C++ should be organized. In short, you usually have a file called main.cpp that contains the entry-point of your program. The rest, in C++, is done in classes most of the time. A class is usually split into two parts, the declaration of the class in a header file, and the implementation of the class in a cpp file. To use a class, you include the corresponding header file. This is the short version, and there is much more to tell, but this should give you a good starting point.

like image 25
Björn Pollex Avatar answered Jan 25 '23 23:01

Björn Pollex