passing values between 2 different c++ files in same project - 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?

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.

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.

Normally you define a function in one cpp file, then declare that function as extern in a header, and include the header in whatever other cpp file needs to use the function. You can then write code that calls the function normally. At link time you need to supply the object files that resulted from both cpp files, and the linker ...links them together, so the function call in one file passes the value correctly as you call the function that was defined in the other cpp file.

Referencing code in a different file typically makes use of #include

Related

Double header inclusion in C++?

I have what seems a relatively simple question, but one that keeps defying my efforts to understand it.
I apologise if it is a simple question, but like many simple questions, I can't seem to find a solid explanation anywhere.
With the below code:
/*foo.c*/
#include "bar.h"
int main() {
return(my_function(1,2));
}
/*bar.h*/
int my_function(int,int);
/*bar.c*/
#include "bar.h" /*is this necessary!?*/
int my_function(int x, int y) {
return(x+y);
}
Simply, is the second inclusion necessary? I don't understand why I keep seeing headers included in both source files. Surely if the function is declared in "foo.c" by including "bar.h," it does not need to be declared a second time in another linked source file (especially the one which actually defines it)??? A friend tried to explain to me that it didn't really matter for functions, but it did for structs, something which still eludes me! Help!
Is it simply for clarity, so that programmers can see which functions are being used externally?
I just don't get it!
Thanks!
In this particular case, it's unnecessary for the reason you described. It might be useful in situations where you have a more complex set of functions that might all depend on each other. If you include the header at the top of the .cpp file, you have effectively forward-declared every single function and so you don't have to worry about making sure your function definitions are in a certain order.
I also find that it clearly shows that these function definitions correspond to those declarations. This makes it easier for the reader to find how translation units depend on each other. Of course, the names of the files might be sufficient, but some more complex projects do not have one-to-one relationship between .cpp files and .h files. Sometimes headers are broken up into multiple parts, or many implementation files will have their external functions declared in a single header (common for large modules).
Really, all inclusions are unnecessary. You can always, after all, just duplicate the declarations (or definitions, in the case of classes) across all of the files that require them. We use the preprocessor to simplify this task and reduce the amount of redundant code. It's easier to stick to a pattern of always including the corresponding header because it will always work, rather than have to check each file every time you edit them and determine if the inclusion is necessary or not.
The way the C language (and C++) is designed is that the compiler processes each .c file in isolation.
You typically launch your compiler (cl.exe or gcc, for example) for one of your c files, and this produces one object file (.o or .obj).
Once all your object files have been generated, you run the linker, passing it all the object files, and it will tie them together into an executable.
That's why every .c file needs to include the headers it depends on. When the compiler is processing it, it knows nothing about which other .c files you may have. All it knows is the contents of the .c file you point it to, as well as the headers it includes.
In your simplified example inclusion of "bar.h" in "bar.c" is not necessary. But in real world in most cases it would be. If you have a class declaration in "bar.h", and "bar.c" has functions of this class, the inclusion is needed. If you have any other declaration which is used in "bar.c" - being it a constant, enum, etc. - again include is needed. Because in real world it is nearly always needed, the easy rule is - include the header file in the corresponding source file always.
If the header only declares global functions, and the source file only implements them (without calling any of them) then it's not strictly necessary. But that's not usually the case; in a large program, you rarely want global functions.
If the header defines a class, then you'll need to include it in the source file in order to define member functions:
void Thing::function(int x) {
//^^^^^^^ needs class definition
}
If the header declares functions in a namespace, then it's a good idea to put the definitions outside the namespace:
void ns::function(int x) {
//^^^^ needs previous declaration
}
This will give a nice compile-time error if the parameter types don't match a previous declaration - for which you'd need to include the header. Defining the function inside its namespace
namespace ns {
void function(int x) {
// ...
}
}
will silently declare a new overload if you get the parameter types wrong.
Simple rule is this(Considering foo is a member function of some class):-
So, if some header file is declaring a function say:=
//foo.h
void foo (int x);
Compiler would need to see this declaration anywhere you have defined this function ( to make sure your definition is in line with declaration) and you are calling this function ( to make sure you have called the function with correct number and type of arguments).
That means you have to include foo.h everywhere you are making call to that function and where you are providing definition for that function.
Also if foo is a global function ( not inside any namespace ) then there is no need to include that foo.h in implementation file.

Importance of declaring variables and functions in header file

I declare all variables and functions in .h file and has become my habit to do that (I'm programming with cocos2dx)
And I read that you should try to include the least in .h file and the most in .cpp file.
Because I declare all variables and functions in .h file, If I need to use another class from another file, then I need to include that class in the .h file to declare that class as a variable.
So I want to know the importance of declaring variables in .h file and .cpp file. I want to know which way is most standard as well.
If there is no difference, then why people would declare variables and functions in private file because declaring a function in .h file requires you to write it again in .cpp file.
ie)
.h file:
class classA {
private:
void function();
};
.cpp file:
void classA::function() {
...do something...
}
What is the importance of declaring variables and functions in header files?
Declare anything that is needed outside of the code in the .cpp file in the header file, and no more. Try to minimise the amount in there as much as possible. The reason for this is that other programmers could be looking at your header (.h) file, it is essentially their API. As an OOP programmer you want to hide as much of the internal workings of your objects as possible i.e. you do not want people using your API to become dependent on factors that may change as the structure of the objects does. Also try and keep the scope of your variables as low as possible. It is better to avoid global variables if you can in general. Passing them as parameters is almost always a better idea. Try to keep variables in the lowest scope possible.
Typically you would have your declarations inside a header file, and your definitions inside the cpp. There are many benefits to doing this, one of the biggest being re-usability. If you have multiple files that need to use a certain class, it is much easier to just include it where needed rather than having to re-declare it.
Being able to separate prototypes from the actual member bodies is also quite useful. This allows you to do things such as having a binary version of the implementation, and still keep the function names publicly available. This way if someone was using your class or library they could see how to use it, but not be able to see how it actually works. This is very important in larger projects and when copyright is involved.
This is a good habit to get into, but can get confusing and overwhelming if you don't stay organized. Common practice is to have an implementation file (.cpp) and a header (.h) for each class, both generally having the same name as the class to improve readability.
You should avoid using a header file just to declare local variables as it's generally best to keep them in the scope where they're needed.
As for your particular sample, you can avoid putting class private methods into the header file using the Pimpl Idiom. You'll have only publicly visible (public/protected) members declared in your header file, all the rest goes to the .cpp:
.h file:
class ClassA {
public:
ClassA();
~ClassA();
void foo();
private:
class ClassAImpl;
ClassAImpl* pImpl;
};
.cpp file:
#include "ClassA.h"
struct ClassAImpl
void function() {
// ...do something...
}
};
ClassA::ClassA()
: pImpl(new ClassAImpl()) {
}
ClassA::~ClassA() {
delete pImpl;
}
void ClassA::foo() {
pImpl->function();
}
Benefits of having a separate .h and .cpp file
Hide Implementation: You can separate the declaration from definition. So say you want to create an API, you could put your actual logic in .cpp (which becomes the library file on compilation) and have the declaration in .h which someone one could use to access the API.
Reduce Compilation time: One benefit of having definition in .cpp and declaration in .h is when you want to make changes to the definition. Such a change, would just change the cpp file and that .cpp will have to be recompiled. If the definition were to be in .h file, all the .cpp files where the .h file is included would have to be recompiled which would take more time.
Improves Readability: Having declaration and definition separate in some ways improves readability.
One of the reasons we have separate header and source files in C++ is because C++ code is unmanaged . It is directly executed by the processor (unlike C#, Java which are executed in a virtual environment). This requires having a header file to hold the symbol information which while being separate from the implementation, acts as an interface to it.
In C and C++, the order in which things are declared is important. Remember that when these languages were designed - compilers were not what they are today. Header files are things that you "include" which describe classes, type-definitions, enums. Now, you can provide implementation (and in the case of C++ template classes, you have to) in the header file. You put the implementation of the stuff in to the .cpp file. You're not writing a function twice (the compiler will have a hissy-fit if you do). You declare or implement them in the header file and then, in the case of the former, you implement them in the C++ file.
Consumers of your code (in a library project, for example), will include the header files (that describe the classes), and then link against an object file (as opposed to .cpp files). Header files provide you, ahead-of-time, the symbols to expect and link against.
Templates are a little weird in this respect (you don't export them), they are header file only (at the moment, I believe).
Modern languages such as C# do not have the concept of header files, because of the way the compiler works. The C# compiler looks at the files as a "whole" and therefore there is no need to forward declare anything or worry about header files. C/C++ compilers do not do this. I am unsure (without going and looking it up) whether or not this was due to compiler technology at the time or a concsious design decision at the time.
You are not duplicating code.

Confused about C++ classes when wanting to use them in another CPP. [Coming from C#]

In OOP, you want to break apart a program into multiple classes.
In C#, you would do as such:
namespace a
{
public class ClassA
{
//Methods...that are defined and have code in them.
}
}
and to use that class, you just do "using namespace a;".
Say I want to create a class in C++, and define them, and put code in them.
class ClassA
{
public:
void methodA();
}
ClassA::methodA()
{
//implementation.
}
To access this implementation, you would just use #include "ClassA.h". I fully understand that, and then you have to implement that code again? That seems counterproductive as I like to spread my project over a lot of classes.
So what would be the proper procedure to implement ClassA and not re-implement all it's methods again?
You don't have to reimplement them in each CPP file, the C++ linker takes care of making sure the definitions get matched together.
All you need is:
A header:
#ifndef FOO_H
#define FOO_H
class Foo{
//Junk goes here
};
#endif
A cpp:
#include "foo.h"
//implementations for junk goes here
void Foo::junk(){
}
And then you can include foo.h. Each cpp will be compiled to a .o file. Than, those .o files are handed to the linker which can figure out where definitions are and piece together the code correctly.
C and C++ have a different way of doing things. As long as you have a declaration for a class, method, or external variable the compiler will happily compile and leave off the actual definition of the methods, classes, etc, for link time. This is simplifying things a lot, but basically the compiler will leave a hint to the linker in the object file, saying that the linker needs to insert the address of the method here.
So you just need to include the "ClassA.h" file and you can compile fine.
Because of this you see some different behavior in C and C++ than you would in C#. For example, in C or C++ it's perfectly fine to have two different items (methods, variables, etc) that are named the same in different files as long as neither one is visible outside the file. Whereas in C# you would have to use different namespaces or different names. Note - not that I'm saying this is good practice, it's just possible.
The .h header files contain the class specification. The corresponding .cpp files contain the implementation and are compiled to .o files. During development, you would include .h files to access the APIs provided by the class. During compilation/linking stage, you would include the .o files also along with your source files to form the final binary. You don't need to implement anything again, w.r.t to the class you are using.

static inline free function [duplicate]

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables.
As others are saying, it has exactly the same meaning as a static function in the .c file itself. This is because there is no semantic difference between .c and .h files; there is only the compilation unit made up of the file actually passed to the compiler (usually named .c) with the contents of any and all files named in #include lines (usually named .h) inserted into the stream as they are seen by the preprocessor.
The convention that the C source is in a file named .c and public declarations are in files named .h is only a convention. But it is generally a good one. Under that convention, the only things that should appear in .h files are declarations so that you generally avoid having the same symbol defined more than once in a single program.
In this particular case, the static keyword makes the symbol be private to the module, so there isn't a multiple-definition conflict waiting to cause trouble. So in that one sense, it is safe to do. But in the absence of a guarantee that the function would be inlined, you take the risk that the function would be instantiated in every module that happened to #include that header file which at best is a waste of memory in the code segment.
I am not certain of what use cases would justify doing this at all in a generally available public header.
If the .h file is generated code and only included in a single .c file, then I would personally name the file something other than .h to emphasize that it isn't actually a public header at all. For example, a utility that converts a binary file into an initialized variable definition might write a file that is intended to be used via #include and could very well contain a static declaration of the variable, and possibly even static definitions of accessor or other related utility functions.
If you define the function in a header file (not simply declare it), a copy of the function will be generated in each translation unit (basically in each cpp file which includes this header).
This may increase the size of your executable, but this may be negligible if the function is small. The advantage is that the most compilers may inline the function, which may increase the code performance.
But there may be a big difference in doing this which wasn't mentioned in any answer. If your function uses a static local variable such as:
static int counter()
{
static int ctr = 0;
return ctr++;
}
Rather than:
//header
int counter();
//source
int counter()
{
static int ctr = 0;
return ctr++;
}
Then each source file including this header will have its own counter. If the function is declared inside the header, and defined in a source file, then the counter will be shared across your whole program.
So saying that the only difference will be performance and code size is wrong.
There is not semantic difference in defining in source file or header file, basically both means the same in plain C when using static keyword that, you are limiting the scope.
However, there is a problem in writing this in header file, this is because every time you include the header in a source file you'll have a copy of the function with same implementation which is much similar to have a normal function defined in header file. By adding the definition in header you are not achieving the what the static function is meant for.
Therefore, I suggest you should have your implementation only in your source file and not in header.
It is usefull in some "header-only" libraries with small inline functions. In a such case you always want to make a copy of the function so this is not a bad pattern. However, this gives you an easy way to insert separate interface and implementation parts in the single header file:
// header.h
// interface part (for user?!)
static inline float av(float a, float b);
// implementation part (for developer)
static inline float av(float a, float b)
{
return (a+b)/2.f;
}
Apple vector math library in GLK framework uses such constuction (e.g. GLKMatrix4.h).

C/C++: Static function in header file, what does it mean?

I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables.
As others are saying, it has exactly the same meaning as a static function in the .c file itself. This is because there is no semantic difference between .c and .h files; there is only the compilation unit made up of the file actually passed to the compiler (usually named .c) with the contents of any and all files named in #include lines (usually named .h) inserted into the stream as they are seen by the preprocessor.
The convention that the C source is in a file named .c and public declarations are in files named .h is only a convention. But it is generally a good one. Under that convention, the only things that should appear in .h files are declarations so that you generally avoid having the same symbol defined more than once in a single program.
In this particular case, the static keyword makes the symbol be private to the module, so there isn't a multiple-definition conflict waiting to cause trouble. So in that one sense, it is safe to do. But in the absence of a guarantee that the function would be inlined, you take the risk that the function would be instantiated in every module that happened to #include that header file which at best is a waste of memory in the code segment.
I am not certain of what use cases would justify doing this at all in a generally available public header.
If the .h file is generated code and only included in a single .c file, then I would personally name the file something other than .h to emphasize that it isn't actually a public header at all. For example, a utility that converts a binary file into an initialized variable definition might write a file that is intended to be used via #include and could very well contain a static declaration of the variable, and possibly even static definitions of accessor or other related utility functions.
If you define the function in a header file (not simply declare it), a copy of the function will be generated in each translation unit (basically in each cpp file which includes this header).
This may increase the size of your executable, but this may be negligible if the function is small. The advantage is that the most compilers may inline the function, which may increase the code performance.
But there may be a big difference in doing this which wasn't mentioned in any answer. If your function uses a static local variable such as:
static int counter()
{
static int ctr = 0;
return ctr++;
}
Rather than:
//header
int counter();
//source
int counter()
{
static int ctr = 0;
return ctr++;
}
Then each source file including this header will have its own counter. If the function is declared inside the header, and defined in a source file, then the counter will be shared across your whole program.
So saying that the only difference will be performance and code size is wrong.
There is not semantic difference in defining in source file or header file, basically both means the same in plain C when using static keyword that, you are limiting the scope.
However, there is a problem in writing this in header file, this is because every time you include the header in a source file you'll have a copy of the function with same implementation which is much similar to have a normal function defined in header file. By adding the definition in header you are not achieving the what the static function is meant for.
Therefore, I suggest you should have your implementation only in your source file and not in header.
It is usefull in some "header-only" libraries with small inline functions. In a such case you always want to make a copy of the function so this is not a bad pattern. However, this gives you an easy way to insert separate interface and implementation parts in the single header file:
// header.h
// interface part (for user?!)
static inline float av(float a, float b);
// implementation part (for developer)
static inline float av(float a, float b)
{
return (a+b)/2.f;
}
Apple vector math library in GLK framework uses such constuction (e.g. GLKMatrix4.h).