C++ compiling of a .o file without the .cc file - c++

I have a program were I was given the compiled .o file but I do not have the original .cc file and also I only have a half-way finished header file. The header file has all the method signatures but is lacking the private variable declarations. I am trying to get this .o file to work with the project but get a segmentation fault at the constructor of the class defined by the .o file. The program compiles. How do I get this to work? The program is a homework assignment and the teacher does not want us to see the .cc file. Also my teacher knows about the issue. I am just trying to figure it out on my own (and hopefully with the help of you guys :) ). I thought I had done this before a while ago with another teacher but did not have any problems. There is a makefile that is used to compile the program.

If you are using a C++ program, and the header file includes class definitions, the class definitions must exactly match those that were used to originally build the file. This is the One Definition Rule. If your professor has removed private variable declarations from the class definitions, you will likely end up with crashes; this is because your different .o files will disagree about the size of the objects defined by those classes.
If your professor wants to hide the implementation of the class, they should use the p/impl pattern. If you want to use the header file, you must remove the mangled class definitions entirely and not attempt to use them (you can use a forward definition as in class Foo; to satisfy any functions which take/return the class as a pointer parameter, however).

Related

C++ "Rules" for keyword inclusion in Header file vs Source/Implementation file

Must be honest, I am getting confused between what keywords go in the function (and sometimes data member) declarations in the header file, versus what goes in the implementation file.
What is the set of rules to follow? For example
(Updated per comments)
Header files don't contain implementation except if the function is declared as "inline"
Data members don't contain a default value, unless if the type is static, const, int/enum (unless C++11)
Public/private/protected usually appear in the header file
"Static" usually appears in the header file, not the implementation file.
Are thee any other rules I can use to follow? Const?
What about for inheritance? I presume "virtual" only goes in header files? If I inherit virtual functions from Class A into Class B, does the header file of Class B have to declare the virtual functions it overrides? What about a pure virtual function in Class A, when I override in Class B would I have to include the pure virtual function definition in the header file of the derived class?
Looks like you are trying to make some formal rules without understanding how it works. But it is really simple, when preprocessor sees #include directive it just replace it with content of that file (it is like command copy whole file and paste it here). So instead of making formal rules just ask yourself questions: should this statement appear in every .cpp file that uses this header? Will they still compile? Do I really need it everywhere, or it can be in only one .cpp file that provides implementation? If answers are yes, then this statement should go to the header, if no to any of them, then put it into .cpp implementation file.
The #include statement in C and C++ is much simpler than you're giving it credit for: it takes the contents of the include'd file, and dumps it straight into your including file. This can be anything (I see a lot of newbie developers in my line of work. If it's a file on disk, at some point someone's tried to include it): even .cpp files. You can, if you want to prove it to yourself, copy & paste the contents of an included file in place of an include - everything should work as before.
For completeness: once the pre-processor has dumped all the included files to where they are asked for, the compiler compiles each file separately. This typically leaves you with a bunch of declarations with no implementation and a bunch of implementations with no declarations: the linker sorts out these references. So if you ever get a linker error, that means that somewhere you've mis-matched something: maybe you declared something twice, or never implemented it.
What we actually have is a series of best practices about what we want in header files and what we want in source files. Typically, we like to have declarations in a header file. In other words, the header file should tell me (the programmer) what things I expect to find in the implementation. Typically, these are declarations: hence why you generally only see access modifiers (public, private, protected) in headers. Some programmers will do "odd" stuff like writing constructors in header files: this is valid, but is generally not expected - you want your header to tell me what things I can use from your code, not how your code works.

Compile cpp without corresponding header

I've just been given my first real C++ application on the job after working through some books learning the language.
It was my understanding that your cpp source files required the cooresponding header, yet one of the libraries in my project is building fine with a number of cpp files that DO NOT include the cooresponding header. This particular cpp implements a class found in a header that has a different name and a number of other pieces of code beyond just the original class declaration.
How is it that the cpp can compile functions belonging to a class that it has no knowledge of?
Can the implementation of these functions be compiled independently and are simply called when a client application using the library (and including the header with the class declaration) calls the corresponding member function? If this is the case, how is the implementation binary referenced by the client application?
(I assume this is the linker...but I would love to have this cleared up).
I anticipate the answer may expose a misunderstanding of mine with regard to the include and compilation process, and I'd really like to learn this aspect of C++ well. Thank you!
When a c++ source file is compiled the first stage it goes through is preprocessing.
When the include directive is reached the file is found and the entire contents of the file, whatever that may be is included into the source file, as if it had been written in the source file itself.
You will be able to define any function from a class in any source file that includes the class's declaration, this is the source file "knowing" about the class / function".
There's also no requirement that the contents of a header and a source file will have any relationship. It's widely considered to be very good practise however.
The implementation of each compilation unit (a source file) is compiled independently. Any function definition could be placed in any compilation unit, and it would make not difference whatsoever. When the compilation units are linked together the usages of every declaration are matched to all the definitions.
The only other pattern that some people might use other than the 1:1 relationship between source files and header files (that I can think of) is that the header files each describe a class and each source file would implement a collection of related functionality. But this is a bad idea (in my opinion) because it would encourage the definitions of various classes to because highly coupled.
These are several questions. You should try to split these.
The name of the files where something is declared is not relavant. The compiler gets the preprocessor output independent from the files that have been read by the preprocessor. The compiler might be use some file/line information in the preprocessed file to issue more readable diagnostic messages.
When you declare a class in a header file and copy that declaration to a implementation file everything works fine as long as you don't change one of the copies of the declaration. This is bad dangerous and should be avoided. Declare anything always once.
When you compile an implementation of a class member function you get a function that the linker can link to your client program. A good tool chain is able to link only the functions that are accessed. So you can separate the interface (in the header files) from the implementation that is provided in a static library. The linker will add each object module in the library to your executable until all symbol references are resolved.

Will everything work the same if I cut and paste my .cpp to the bottom of my .h?

I have a very simple class and I'd like to consolidate it to a single .h file. Will everything work the same if I cut and paste the guts of my .cpp to the bottom of my .h?
In particular, there are static member variable initializations int MyClass::myStaticVar = 0; outside of any class definition at the top of the .cpp, and following that, there are static member function implementations void MyClass::myStaticMethod() {...}. Some non-static member functions are already being implemented in the .h, not the .cpp. So you can see there are some nuances here that I'd like to clarify.
Edit So far, what I'm getting is:
This is naughty, but it will work if you only #include the .h once.
It breaks the convention and doesn't really work like a .h so it might
as well be named .doofus.
Now, for example, look at the TUIO C++ bindings. A lot of the classes consist of one .h file, no cpp (TuioPoint.h, TuioCursor.h, TuioObject.h, etc). I don't think this is so bad...
If you're left with a single cpp file in the entire project, then it will work (but it's bad practice). If you have two cpp files that both include that header, you're breaking the one definition rule, and you (should) get linker errors.
You can do this if (A) All the functions are templates (in fact, you must in this case), or (B) all the functions are marked as inline.
[Edit]
The reason you aren't already having problems is a function defined in the class definition is automatically marked as inline. Thus: no problems. However, if the function is defined outside of the class definition, it should be in a cpp file. Also, static members should always be in a cpp file.
[Edit2] The reason non-inline, non-template functions and File scope varaibles (globals and static members) should always be in a cpp file, is that when the compiler finds that line of code, it creates the function/variable right there. Obviously, it must be created once to be used. Why not in a header file? Because then if the header is included in two cpp files, it will be created in two places (I have hpp files at work that are literally included in several thousand cpp files). C++ has a "one-definition rule" where each function/object can only be defined/created once, to prevent this obvious error:
int MyClass::myStaticVar = 0;
int MyClass::myStaticVar = 7;
Which would it use? You've just created two variables with the same name! So this isn't allowed, even if they were exactly the same, (except for inline/template). Each cpp file is compiled once and only once (unless for some oddball reason it's included from something else), which prevents accidental violations of the one-definition rule.
Also, hpp files are for declarations, and cpp files are for definitions/instantiations.
what good would the .h file be anymore? you can't have multiple .cpp files #include this .h file. And if this .h is only included by a single .cpp, then why do you need the .h file in the first place - just put everything in the .cpp.
In addition to Mooings answer you might want to consider the compile/link process for a while.
The compiler compiles the .cpp files, not the .h files (by convention).
This has the consequence that for each .cpp file you need the definitions for the classes you reference in order to create instructions for the code in the .cpp. The .h files provides that.
What you do not want is identical pieces of code being duplicated across your program, which would be the consequence of compiling .cpp files including headers with implementations(what you are suggesting); hence the one definition rule.
In a one .cpp-file project as Mooing suggests you can of course abuse this to your delight as long as you have a .cpp with a main and only one set of includes.
Essentially, this is what #include does (it pastes the header into the cpp, basically doing the same thing in a sense). So, yes, everything SHOULD work out fine, assuming no odd cases. I can't see why you would want to do this though. You'd be better off just flat out defining the functions and such in the class definition or just using #include. Is there any reason you're choosing not to?
EDIT: In response to your edits, why are you implementing members in the header? I'd suggest moving those to the .cpp unless this is a template class or some similar special case. Use the header for prototype and decleration, use the cpp for definition. That should solve any issues for you.

C++ header file question

I was trying out some c++ code while working with classes and this question occurred to me and it's bugging me a little.
I have created a header file that contains my class definition and a cpp file that contains the implementation.
If I use this class in a different cpp file, why am I including the header file instead of the cpp file that contains the class implementations?
If I include the class implementation file, then the class header file should be imported automatically right (since i've already included the header file in the implementation file)? Isn't this more natural?
Sorry if this is a dumb question, i'm genuinely interested in knowing why most people include .h instead of .cpp files when the latter seems more natural (I know python somewhat, maybe that's why it seems natural to me atleast). Is it just historical or is there a technical reason concerning program organisation or maybe something else?
Because when you're compiling another file, C++ doesn't actually need to know about the implementation. It only needs to know the signature of each function (which paramters it takes and what it returns), the name of each class, what macros are #defined, and other "summary" information like that, so that it can check that you're using functions and classes correctly. The contents of different .cpp files don't get put together until the linker runs.
For example, say you have foo.h
int foo(int a, float b);
and foo.cpp
#include "foo.h"
int foo(int a, float b) { /* implementation */ }
and bar.cpp
#include "foo.h"
int bar(void) {
int c = foo(1, 2.1);
}
When you compile foo.cpp, it becomes foo.o, and when you compile bar.cpp, it becomes bar.o. Now, in the process of compiling, the compiler needs to check that the definition of function foo() in foo.cpp agrees with the usage of function foo() in bar.cpp (i.e. takes an int and a float and returns an int). The way it does that is by making you include the same header file in both .cpp files, and if both the definition and the usage agree with the declaration in the header, then they must agree with each other.
But the compiler doesn't actually include the implementation of foo() in bar.o. It just includes an assembly language instruction to call foo. So when it creates bar.o, it doesn't need to know anything about the contents of foo.cpp. However, when you get to the linking stage (which happens after compilation), the linker actually does need to know about the implementation of foo(), because it's going to include that implementation in the final program and replace the call foo instruction with a call 0x109d9829 (or whatever it decides the memory address of function foo() should be).
Note that the linker does not check that the implementation of foo() (in foo.o) agrees with the use of foo() (in bar.o) - for example, it doesn't check that foo() is getting called with an int and a float parameter! It's kind of hard to do that sort of check in assembly language (at least, harder than it is to check the C++ source code), so the linker relies on knowing that the compiler has already checked that. And that's why you need the header file, to provide that information to the compiler.
The magic is done by the linker. Every .cpp when compiled will generate an intermediate object file with all the exported and imported symbols in a table. The linker will reconcile them. In other words, you just have to include the header, and every time you will reference the included class, the compiler will put the signature of the referenced class in the symbol table.
If you include the .cpp file, you will have the same code compiled twice and you will get linking errors, as the same symbol will be found twice by the linker and hence it will be ambiguous.
One technical reason is compilation speed. Let's suppose your class uses 10 other classes (e.g. as types for member variables). Including the long .cpp files for all 10 classes would make your class compile much slower (i.e. maybe 2 seconds instead of 1 second).
Another reason is hiding the implementation. Let's suppose you are writing a class to be used by 10 other teams in your company. All they have to know and learn about your class is in the .h file (public interface). You can freely do whatever you want in the .cpp file (implementation), you may change it as often you want, they won't care. But if you change the .h file, they may have to adjust their code using your class.
For each method body, it's your choice whether to put it to the .h file or to the .cpp file. If it's in the .h file, the compiler can inline it when called, which may make the code a bit faster. But compilation will be slower, and the temporary .o (.obj) files may become larger (because each of them will contain the compiled method body), and the program binary (.exe) may become larger, because the function body takes space as many times it is inlined.

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

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