Say I have 4 classes A, B, C, and D, and I want to use all 4 within a class that is implementing pure virtual functions from another .h file User. My question is how can I include those 4 classes into one .h so the .cpp of that .h will allow me to call those functions within the classes.
This is what I have tried so far:
#include "User.h"
#include "A.h"
#include "B.h"
#include "C.h"
#include "D.h"
Class create : public User, public A, public B, public C, public D
{
public:
create();
virtual ~create();
bool a1();
bool b1();
bool c1();
bool d1();
int a2();
int b2();
int c2();
int d2();
};
Then when I try to call those functions (declared in A.cpp, B.ccp, C.cpp, D.cpp) in the create.cpp I am being told "undefined reference to A::a1( )... and so on.
Does this make sense?
The undefined reference to ... error is not a compilation error. It is a linker error.
Basically, the linker is a program that puts together multiple pieces of object code (i.e. compiled code) to create an executable file. In your case, the compiler knows that a method A::a1() must exist, agrees with its declaration (the name and parameters) and doesn't complain about its usage. However, the liker cannot find its definition (basically, its compiled implementation).
You provided too few details for an explanation of how to properly compile and link your code, but the process should consist of compilation of each .cpp file, that contains implementations of your classes. Some details about linking can be found in the following questions:
C++ linking object's files (G++)
Linking files in g++
You probably need to do something like this:
g++ source_code.cpp A.cpp B.cpp C.cpp D.cpp
or something like that. If you need to link the object code,
replace the .cpp extension with .o once you compile each individual .cpp file into an .o file.
Related
My 'Headers.h' file includes basic c++ Headers
#include <iostream>
#include <cstring>
// and many header files.
wrote a function definition for file exist check and saved it in 'common_utility.h' - ifFileExist()
common_utility.h
bool ifFileExist()
{
// ... My code
}
Wrote code for Class A
classA.h
class A
{
// Contains class A Declarations.
};
classA.cpp
// Contains
#include "Headers.h"
#include "common_utility.h"
#include "classA.h"
// class A Method definition
Wrote Code for Class B
I am using class A in Class B.
classB.h
class B
{
// Contains class A Declarations.
}
classB.cpp
// Contains
#include "Headers.h"
#include "common_utility.h"
#include "classA.h"
#include "classB.h"
// class B Method definition
// calling the function ifFileExist() in class B also.
wrote code for main program
main.cpp
// Contains
#include "Headers.h"
#include "common_utility.h"
#include "classA.h"
#include "classB.h"
// I am using class A and Class B in main program
// calling the function ifFileExist() in Main program also.
When I compile the whole program as
g++ -std=c++0x classA.cpp classB.cpp main.cpp -o main
I am getting the following error.
In function ifFileExist()': classB.cpp:(.text+0x0): multiple
definition ofifFileExist()'
/tmp/ccHkDT11.o:classA.cpp:(.text+0x2b6e): first defined here
So I decleard ifFileExist() function in Headers.h as extern.
extern bool ifFileExist();
But still I am getting the same error.
I am including 'Headers.h' in every .cpp file. That file contains basic c++ libraries. But I didn't get any mulitple definition error for that header files.
But only in my own function, I am getting the error 'multiple definition'.
I want to use 'common_utility.h' file, when ever I need to use it. If I doesn't need to use the common_utility functions in my main program, simply I should not include it.
I want my program to run in the every following cases.
g++ -std=c++0x classA.cpp main.cpp -o main
g++ -std=c++0x classB.cpp> main.cpp -o main
g++ -std=c++0x classA.cpp classB.cpp main.cpp -o main
I shouldn't get mulitple definition error at any cases. What Should I do now?
Since I could not find any complete (in my view) duplicate for this question, I am going to write a (hopefully) authoritive and complete answer.
What is One Definition Rule and why should I care
A One Definition Rule, usually dubbed ODR, is a rule which states (simplified) that any entity (informal term) used in the program should be defined once, and only once. An entity which is defined more than once is often causing a compilation or linker error, but sometimes can be left undetected by the compiler and lead to very hard-to-trace bugs.
I am not going to formally define entity here, but one can think of it as a function, variable or class. Before going further, one should very clear understand the difference between definition and declaration in C++, since while double definition is prohibited, double declaration is usually unavoidable.
Definition vs. declaration
Every entity used in the code should be declared in the given translation unit (translation unit is usually a cpp source file together with all header files included in it, directly or indirectly through other header files). The way an entitty is declared differes based on the entity itself. See below on how to declare different types of entities. Entities are often declared in header files. Since most complex application has more than one translation unit in it (more than one cpp file), and different cpp files often include the same headers, an application is likely to have multiple declarations for many entities used. Like I said above, this is not a problem.
Every entity used in the application, must be defined once and only once. The term 'application' is used a bit loosely here - for example, libraries (both static and dynamic) can have entities (at this point usually called symbols) left undefined within them, and an executable which was linked to use a dynamic library can have a symbol undefined as well. Instead, I refer to the application is an ultimate running something, after all the libraries have been statically or dynamically linked into it, and symbols resolved.
It is also worth noting that every definition serves as a declaration as well, meaning, that whenever you define something, you are also declaring the same thing.
As with declaration, the way to define an entity differes by the type of entity. Here is how one can declare/define 3 basic types of entities - variables, classes and functions - based on it's type.
Variables
Variables are declared using following construct:
extern int x;
This declares a variable x. It does not define it! A following piece of code will be compiled OK, but an attempt to link it without any other input files (for example, with g++ main.cpp) will produce a link-time error due to undefined symbols:
extern int x;
int main() {
return x;
}
The following piece of code defines variable x:
int x;
If this single line were to be put into file x.cpp, and this file compiled/linked together with main.cpp from above with g++ x.cpp main.cpp -o test it would compile and link without problems. You could even run resulting executable, and if you are to check exit code after the executable was run, you'd notice it is 0. (Since global variable x would be default-initialized to 0).
Functions
Functions are declared by providing their prototypes. A typical function declaration looks like following:
double foo(int x, double y);
This construct declares a function foo, returning double and accepting two arguments - one of type int, another of type double. This declaration can appear multiple times.
Following code defines above mentioned foo:
void foo(int x, double y) {
return x * y;
}
This definition can only appear once in the whole application.
Function definition has an additional quirk to variable definition. If above definition of foo were to put into header file foo.h, which in turn would be included by two cpp files 1.cpp and 2.cpp, which are compiled/linked together with g++ 1.cpp 2.cpp -o test you would have a linker error, saying that foo() is defined twice. This might be prevented by using following form of foo declaration:
inline void foo(int x, double y) {
return x * y;
}
Note inline there. What it tells compiler is that foo can be included by multiple .cpp files, and this inclusion should not produce linker error. Compiler have several options on how to make this happen, but it can be relied upon to do it's job. Note, it would still be an error to have this definition twice in the same translation unit! For example, following code will produce a compiler error
inline void foo() { }
inline void foo() { }
It is worth noting, that any class method defined within the class is implictly inline, for example:
class A {
public:
int foo() { return 42; }
};
Here A::foo() is defined inline.
Classess
Classess are declared by following construct:
class X;
Above declaration declares class X (and at this point X is formally called an incomplete type), so that it can be used when information about it contents, such as it's size or it's members is not needed. For example:
X* p; // OK - no information about class X is actually required to define a pointer to it
p->y = 42; // Error - compiler has no idea if X has any member named `y`
void foo(X x); // OK - compiler does not need to generated any code for this
void foo(X x) { } // Error - compiler needs to know the size of X to generate code for foo to properly read it's argument
void bar(X* x) { } // OK - compiler needs not to know specifics of X for this
A definition of class is well-known to everybody, and follows this construct:
class X {
public:
int y;
};
This makes a class X defined, and now it can be used in any context. An important note - class definition has to be unique per tralnlation unit, but does not have to be unique per application. That is, you can have X defined only once per translation unit, but it can be used in multiple files linked together.
How to properly follow ODR rules
Whenever a same entity is defined more than once in the resulting application, so-called ODR violation happenes. Most of the time, a linker will see the violation and will complain. However, there are cases when ODR violation does not break linking and instead causes bugs. This might happen, for example, when the same .cpp file defining a global variable X is put into both application and dynamic library, which is loaded on demand (with dlopen). (Yours trully spent a couple of days trying to trace a bug happened because of that.)
A more conventional causes of ODR violations are:
Same entity defined twice in the same file in the same scope
int x;
int x; // ODR violation
void foo() {
int x;
} // No ODR violation, foo::x is different from x in the global scope
Prevention: don't do this.
Same entity defined twice, when it was supposed to be declared
(in x.h)
int x;
(in 1.cpp)
#include <x.h>
void set_x(int y) {
x = y;
}
(in 2.cpp)
#include <x.h>
int get_x() {
return x;
}
While the wisdom of above code is questionable at best, in serves a point of illustrating ODR rule. In the code above, variable x is supposed to be shared between two files, 1.cpp and 2.cpp, but was coded incorrectly. Instead, the code should be following:
(in x.h)
extern int x; //declare x
(in x.xpp)
int x; // define x
// 1.cpp and 2.cpp remain the same
Prevention
Know what you are doing. Declare entities when you want them declared, do not define them.
If in the example above we'd use function instead of the variable, like following:
(in x.h)
int x_func() { return 42; }
We would have a problem which could be solved in two ways (as mentioned above). We could use inline function, or we could move definition to the cpp file:
(in x.h)
int x_func();
(in x.cpp)
int x_func() { return 42; }
Same header file included twice, causing the same class defined twice
This is a funny one. Imagine, you have a following code:
(in a.h)
class A { };
(in main.cpp)
#include <a.h>
#include <a.h> // compilation error!
The above code is seldom appearing as written, but it is quite easy to have the same file included twice through the intermediate:
(in foo.h)
#include <a.h>
(in main.cpp)
#include <a.h>
#include <foo.h>
Prevention Traditional solution to this is to use so-called include guards, that is, a special preprocessor definitions which would prevent the double-inclusion. In this regard, a.h should be redone as following:
(in a.h)
#ifndef INCLUDED_A_H
#define INCLUDED_A_H
class A { };
#endif
The code above will prevent inclusion of a.h into the same translation unit more than once, since INCLUDED_A_H will become defined after first inclusion, and will fail #ifndef on all subsequent ones.
Some compilers expose other ways to control inclusion, but to date include guards remain the way to do it uniformely across different compilers.
Before actually compiling source the compilation unit is generated from .cpp files. This basically means that all preprocessor directives are computed: all #include will be replaces with content of the included files, all #define'd values will be substituted with corresponding expressions, all #if 0 ... #endif will be removed, etc. So after this step in your case you'll get two pieces of C++ code without any preprocessor directives that will both have definition of same function bool ifFileExist() that is why you get this multiple definition error.
The fast solution is to mark it as inline bool ifFileExist(). Basically you ask compiler to replace all corresponding function calls with content of the function itself.
Another approach is to live the declaration of your function in common_utility.h and move definition to common_utility.cpp
I have three files.
Wood.cpp
Brick.cpp
Wall.cpp
And my main() function is in Brick.cpp:
Now, when I run the project, it throws error that the className (which is in Wall.cpp) is undefined. What should I do?
I think the main() function is run before the delaration of Wall.cpp file.
You need a way to tell the c++ compiler what function would be available and implemented, in C++ the way is using headers files:
Example:
File a.hpp
class A {
// variable members
// function signatures or inline functions
};
File a.cpp
// Implementation of functions in class A and initialization of static variables in A
File b.hpp
#include "a.hpp"
// Could use class A
class B {
A m_a_member_variable;
}
File b.cpp
// Implementation of functions in class B and initialization of static variables in B that could use classes and declarations in a.hpp (ex: class A)
I think the main() function is run before the delaration of Wall.cpp file. there is no run before while compiling. also, the compilation order is defined by the compiler.
you need to include the header (ussualy *.h, *.hpp, *.hh) file (if you have one, otherwise you have to create one) where className is defined into the source file where you use this class.
for the compiler it is enough to know the declaration (which is in the header) of a class to compile the source. the declaration is then necessary for the linker.
I need help translating a concept from Java to C++.
In Java, when you create a class and give it methods (functions), you must define the function in that class so that it can be properly called by any class instance that might want to.
For example, in the class Employee you'd declare and define the method salaryRaise(int amount).
Whenever an Employee object wants to use it, it calls Employee.salaryRaise(i) and Java knows exactly where to find it - in the Employee class.
In C++, functions are declared in .h files and then defined somewhere else.
How does the compiler know where to find this method?
That is really the job of the linker, not the compiler. The compiler will call the function referencing a symbol that is yet undefined. The linker will then get the different translation units and resolve the symbols by name (that is, the mangled names that encodes additional information as the namespaces, types of the arguments...)
You declare the function in the header (.h) file. That header file then gets #includeed in any other files where you need to use the function. This satisfies the compiler, because it knows the signature of the function and how to call it.
The function is then defined in the source (.cpp) file. The source file includes it's own header file, so that when you compile it, you end up with an object file containing the complete compiled code for that function.
The linker then links any parts of your code where you've called the function (i.e. the files where you included the header), with the actual code for that function.
EDIT with example:
Foo.h:
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
int fooFunction(double a);
};
#endif
Foo.cpp:
#include "Foo.h"
int Foo::fooFunction(double a)
{
// Function definition
return 1;
}
Compiling Foo.cpp generates Foo.obj which contains the complete definition for fooFunction. So far so good.
Bar.h:
#ifndef BAR_H
#define BAR_H
#include "Foo.h"
class Bar
{
public:
void barFunction();
};
#endif
Bar.cpp:
#include "Bar.h"
void Bar::barFunction()
{
Foo foo;
int returnValue = foo.fooFunction(2.0);
}
Bar.cpp includes Bar.h which in turn includes Foo.h. When Bar.cpp gets preprocessed therefore, the declarations for Foo::fooFunction are inserted at the top of the file. So, when the statement int returnValue = foo.fooFunction(2.0); is compiled, the compiler knows how to emit the machine instructions to call fooFunction because it knows the type of the return value (int) and it knows the types of the parameters (a double, and an implicit this pointer for the foo object). Because no function definition was provided, the function will not be inlined (inlining means the entire code for the function is copied into the point at which it is called). Instead, a pointer to the memory address of the function is used to call it. Because a pointer is being used, the compiler doesn't care about the definition - all it needs to know is "I need to call a function X at memory location Y with parameters A and B, and I need to have an int sized memory section ready to store the return value, and I'll assume that the code at that address knows how to perform the function". However, the compiler has no way to know what the address of that function will be in advance (because the function definition lives in a separate .cpp file and will be part of a separate compilation job AKA translation unit).
That's where the linker comes in. Once all the translation units have been compiled (which could be in any arbitrary order), the linker goes back to the compiled code for Bar.cpp and links the two together by filling in the address for the now compiled definition of fooFunction at the point at which it is called in Bar.cpp, thus making the compiled code fully executable.
In C++, functions are declared in .h files and then defined somewhere else. How does the compiler know where to find this method?
Because you tell it where to find it when you provide the definition of the method.
Consider a hypothetical header file:
class Gizmo
{
public:
bool Foo();
};
Now we will define the Foo method above in another CPP file:
bool Gizmo::Foo()
{
return true;
}
Here's the paraphrased dialogue you have with the above definition:
Ok, compiler. I'm defining a function which returns a bool. The
function is part of the class Gizmo, and the function is named Foo.
The function takes no parameters. The definition of the function is:
return true.
The scope resolution token :: separates a name of an enclosing class and the name of the function.
If you had left that Gizmo:: bit out, and instead wrote:
bool Foo()
{
return true;
}
The you would still be defining a function named Foo which takes no parameters and returns a bool, but now instead of defining it to be part of Gizmo, you are defining it to be on it's own. A so-called "free function" or "global function." This would compile just fine, but you would get an "unresolved external" linker error if some other code somewhere was trying to use Gizmo::Foo().
When the compiler transforms your source to binary, it usually builds intermediary files (aka object files) that contain (among other things) the member functions of a class.
At the time of linking the intermediary files are translated into machine code. If all member functions used can be resolved at that time, all is good, otherwise you get a linking error.
This way, you can place the definition of member functions anywhere in the project -- as long as the linker finds what it needs, it can build the binary. It is not advised, however as this approach will make reading/understanding the class purpose/mechanic harder for humans
A compiler will typically have a compilation stage and a linking stage. The compilation stage compiles source files into object files. The linking stage will collect the object files and create an executable image. During the linking stage, symbols that were left unresolved in the compilation stage get resolved. This is not much different for either Java and C++. For example, it is how a Java class can call methods on a different Java class.
In C++ you determine the body by class name followed by :: and then method declaration:
class Employee
{
void salaryRaise(int amount); // Now, compiler knows this method belongs to
// the class Employee
};
Then you can define the body:
void Employee::salaryRaise(int amount) // Now, compiler knows everything about
{ ^^^^^^^^^^ // definition of the method
}
For generating object files (and executable binary), you have to pass the .cpp files to the compiler(actually the linker). Therefore everything is visible to the compiler.
In your header file, you prototype/forward declare the class like this.
class Foo
{
private:
int m_Fooint;
int m_Fooint2;
public:
Foo(int a, int b);
int getFooTotal();
};
Then you would define the member functions like this
Foo::Foo(int a, int b) // prototypes names don't have to be the same
{
Foo::m_Fooint = a;
Foo::m_Fooint2 = b;
}
int Foo::getFooTotal()
{
return Foo::m_Fooint + Foo::m_Fooint2;
}
Besides the constructor and destructor, you need to have the data type. Even if it's void and not returning anything.
So you might have something such as
float Foo::getSomeFloat();
or
double Foo::getSomeDouble();
or you can even return an object
OtherClass Foo::getOtherClassObject();
So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?
Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.
For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:
class A;
This lets you use pointer and reference types (A* and A&), though not A itself. It also doesn't let you call members.
Example:
// a.h
struct B; // forward declaration
struct A {
void foo(B* b); // pointers and references to forward-declared classes are ok
};
// b.h
struct A; // forward declaration
struct B {
void bar(A& a); // pointers and references to forward-declared classes are ok
};
// a.cpp
#include "a.h"
#include "b.h"
void A::foo(B* b) {
b->bar(*this); // full declaration of B visible, ok to call members now
}
// b.cpp
#include "a.h"
#include "b.h"
void B::bar(A& a) {
a.foo(this); // full declaration of A visible, ok to call members now
}
Each class (A and B) should have a header file and an implementation file.
Each header file (e.g. A.h) should not include the other header file (e.g. B.h) but may include a forward reference to the other class (e.g. a statement like class B;), and may then use pointers and/or references to the other class in its declaration (e.g. class A may contain a B* as a data member and/or as a method parameter).
Each CPP file (e.g. A.cpp) may include more than one header file (e.g. A.h and B.h). It's recommended that each CPP file should include its own header file first (e.g. A.cpp should include A.h and then B.h, whereas B.cpp should include B.h and then A.h).
Each header file should contain only the declaration, and not the definition of the class: for example it will list the signatures of the class' methods, but not the method bodies/implementations (the method bodies/implementations will be in the .cpp file, not in the header file). Because the header files don't contain implemention details, they therefore don't depend on (don't need to see) details of other classes; at most they need to know that, for example, B is the name of a class: which it can get from a forward declaratin, instead of by including a header file in another header file.
You can also use forward declarations to get around the issue.
Try putting #ifndef, #define and #endif around your .h files.
I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics.
I have distilled the problematic code as follows:
template_test.h:
template<class BaseClass>
class Templated : public BaseClass
{
public:
Templated(int a);
virtual int Foo();
};
class Base
{
protected:
Base(int a);
public:
virtual int Foo() = 0;
protected:
int b;
};
template_test.cpp:
#include "template_test.h"
Base::Base(int a)
: b(a+1)
{
}
template<class BaseClass>
Templated<BaseClass>::Templated(int a)
: BaseClass(a)
{
}
template<class BaseClass>
int Templated<BaseClass>::Foo()
{
return this->b;
}
main.cpp:
#include "template_test.h"
int main()
{
Templated<Base> test(1);
return test.Foo();
}
When I build the code, I get linker errors, saying that the symbols Templated<Base>::Templated(int) and Templated<Base>::Foo() cannot be found.
A quick Google suggests that adding the following to main.cpp will solve the problem:
template<> Templated<Base>::Templated(int a);
template<> int Templated<Base>::Foo();
But this does not solve the problem. Adding the lines to main.cpp does not work either. (Though, interestingly, adding them to both gives 'multiply defined symbol' errors from the linker, so they must be doing something...)
However, putting all the code in one source file does solve the problem. While this would be ok for the noddy example above, the real application I'm looking at would become unmanageable very fast if I was forced to put the whole lot in one cpp file.
Does anyone know if what I'm doing is even possible? (How) can I solve my linker errors?
I would assume that I could make all the methods in class Templated inline and this would work, but this doesn't seem ideal either.
With templated classes, the definitions must be available for each translation unit that uses it. The definitions can go in a separate file, usually with .inl or .tcc extension; the header file #includes that file at the bottom. Thus, even though it's in a separate file, it's still #included for each translation unit; it cannot be standalone.
So, for your example, rename template_test.cpp to template_test.inl (or template_test.tcc, or whatever), then have #include "template_test.inl" (or whatever) at the bottom of template_test.h, just before the #endif of the include guard.
Hope this helps!
The problem is that when your Templated file is compiled, the compiler doesn't know what types it will need to generate code for, so it doesn't.
Then when you link, main.cpp says it needs those functions, but they were never compiled into object files, so the linker can't find them.
The other answers show ways to solve this problem in a portable way, in essence putting the definitions of the templated member functions in a place that is visible from where you instantiate instances of that class -- either through explicit instantiation, or putting the implementations in a file that is #included from main.cpp.
You may also want to read your compiler's documentation to see how they recommends setting things up. I know the IBM XLC compiler has some different settings and options for how to set these up.
The C++ FAQ-lite covers this, and a couple of ways round it.
You don't have to make all the methods "inline", but you should define the method bodies in template_test.h, rather in template_test.cpp.
Some compilers can handle this split, but you have to remember that at one level, templates are like macros. for the compiler to generate the a template for your particular , it needs to have the template source handy.
When the compiler is compiling main.cpp, it sees the class definition has member function declarations, but no member function defintions. It just assumes that there must be a definition of "Templated" constructor and Foo implementation somewhere, so it defers to the linker to find it at link time.
The solution to your problem is to put the implementation of Templated into template.h.
eg
template<class BaseClass>
class Templated : public BaseClass
{
public:
Templated(int a) : BaseClass(a) {}
virtual int Foo() { return BaseClass::b; }
};
Interestingly, I could get your code to link by putting this at the end of template_test.cpp.
void Nobody_Ever_Calls_This()
{
Templated<Base> dummy(1);
}
Now the compiler can find an instance of Templated to link with. I wouldn't recommend this as a technique. Some other file might want to create a
Templated<Widget>
and then you'd have to add another explicit instantiation to template_test.cpp.