So, i have taken some ready code from a co-worker and build my own into theirs. The code compiles without warnings. The header contains a class and some declarations. The cpp file implements the methods. If i try to declare an extra method into the header file, there's absolutely no problem. But when i try to declare an extra variable (specifically char*) and use it into the cpp file, it compiles but creates abnormailites(programm does not do what it was doing, even with one declaration). If i declare the variable into the cpp file it works fine. I'm using dev c++. Is there maybe a linker issue?
this creates problems:
.h file:
class foo{
char* foo_char;
bool a_method();
}
.cpp file:
bool a_method(){
//do smthing
}
this is not:
.h file:
class foo{
bool a_method();
}
.cpp file:
char* foo_char;
bool a_method(){
//do smthing
}
Based on the initial writeup, I thought it might be an external variable declaration, but now we have sample code to work with. Let's assume this is real code.
This is the code from the latest edit of the question:
foo.h
class foo {
char* foo_char;
bool a_method();
}
foo.cpp
bool a_method() {
//do smthing
}
Okay, this is wrong. First, you need it to really be this:
bool foo::a_method() {
}
And your second example doesn't really make sense at all. You've moved your variable outside of the class definition, so it's no longer a class variable. Maybe that's what you want, but I don't think so.
And, of course, you still aren't indicating that a_method() is defined as a class method of foo when you write the code.
Try fixing this stuff and see if you do better.
Do you have a book? It seems to me you need to back up and read from the beginning. This is the very most basic parts of programming.
Related
I am developing a project in which I have a vendor library, say vendor.h, for the specific Arduino-compatible board I'm using which defines class HTTPClient that conflicts with an Arduino system library, HTTPClient.h, which also defines class HTTPClient.
These two classes are unrelated other than having the same name, and the vendor implementation of an HTTP client is far less capable than the Arduino system library's implementation, so I'd prefer to use the latter. But I can't omit including the former, because I need quite a bit from the vendor.h. Essentially, I have the problem posed here, but with classes rather than functions. I have the full code of both, but given that one is a system library and the other is a vendor library, I'm reluctant to fork and edit either, as that adds lots of merging work down the road if either of them are updated, so my preference would be to find a tidy solution that doesn't edit either header.
I've tried a variety of solutions posted in other SO questions:
I do not want to leave out either header, as I need vendor.h for quite a few things and need the capabilities of HTTPClient.h's client implementation
Proper namespaces in the headers would solve the problem, I would prefer to avoid editing either header
I tried wrapping the #include <HTTPClient.h> in a namespace in my main.cpp, but that caused linking errors, as it's not a header-only library, so the header & cpp weren't in the same namespace
I tried a simple wrapper as proposed for the function in the above linked SO question in which the header contained just a forward declaration of my wrapper class & the associated cpp contained the actual class definition. This gave a compiler error of error: aggregate 'HTTP::Client client' has incomplete type and cannot be defined (Code sample of this attempt below)
main.cpp:
#include <vendor.h>
#include "httpclientwrapper.h"
HTTP::Client client;
httpclientwrapper.h:
#ifndef INC_HTTPCLIENTWRAPPER_H
#define INC_HTTPCLIENTWRAPPER_H
namespace HTTP {
class Client;
}
#endif
httpclientwrapper.cpp:
#include "httpclientwrapper.h"
#include <HTTPClient.h>
namespace HTTP {
class Client : public ::HTTPClient {};
}
In that example, I can't inherit from HTTPClient in a class definition in my header, as that will reintroduce the duplicate class name to the global namespace in my main program (hence the perhaps misguided attempt to see if a forward declaration would do the trick). I suspect that I can resolve the issue by completely duplicating the class definition of HTTPClient in my wrapper class above rather than trying to use inheritance. I would then add member definitions to my wrapper cpp which pass the call to HTTPClient's members. Before I go through the trouble of rewriting (or more likely, copy/pasting) the entire HTTPClient definition from HTTPClient.h into my own wrapper, I was wondering if there was a better or more proper way to resolve the conflict?
Thanks for you help!
As a solution was never proposed, I'm posting an answer that summarizes my research and my ultimate resolution. Mostly, I encourage the use of namespaces, because proper uses of namespaces would have eliminated the conflict. However, Arduino environments try to keep things simple to lower the barrier of entry, eschewing "complicated" features of C++, so more advanced use cases will likely continue to run into issues like this. From other SO answers and forum posts (cited where I could), here are some methods for avoiding name conflicts like this:
If you can edit the source
Edit the source code to remove the conflict or add a namespace to one of both libraries. If this is an open source library, submit a pull request. This is the cleanest solution. However, if you can't push your changes back upstream (such as when one is a system library for some hardware), you may end up with merge issues down the road when the maintainer/developer updates the libraries.
If you can't edit the source
Credit for part of this: How to avoid variable/function conflicts from two libraries in C++
For libraries that are header only libraries (or all functions are inline)
(ie, they have only a .h file without a .o or .cpp)
Include the library inside a namespace. In most code, this is frowned upon as poor form, but if you're already in a situation where you are trying to cope with a library that doesn't contain itself nicely, it's a clean and simple way to contain the code in a namespace and avoid name conflicts.
main.cpp
namespace foo {
#include library.h
}
int main() {
foo::bar(1);
}
For libraries with functions
The above method will fail to link at compile time, because the declarations in the header will be inside the namespace, but the definitions of those functions are not.
Instead, create a wrapper header and implementation file. In the header, declare your namespace and functions you wish to use, but do not import the original library. In the implementation file, import your library, and use the functions inside your new namespaced functions. That way, the one conflicting library is not imported into the same place as the other.
wrapper.h
namespace foo {
int bar(int a);
}
wrapper.cpp
#include "wrapper.h"
#include "library.h"
namespace foo {
int bar(int a) {
return ::bar(a);
}
}
main.cpp
#include "wrapper.h"
int main() {
foo::bar(1);
}
You could also, for the sake of consistency, wrap both libraries so they're each in their own namespace. This method does mean that you will have to put in the effort to write a wrapper for every function you plan to use. This gets more complicated, however, when you need to use classes from the library (see below).
For libraries with classes
This is an extension of the wrapper function model from above, but you will need to put in more work, and there are a few more drawbacks. You can't write a class that inherits from the library's class, as that would require importing the original library in your wrapper header prior to defining your class, so you must write a complete wrapper class. You also cannot have a private member of your class of the type from the original class that you can delegate calls to for the same reason. The attempt at using a forward declaration I described in my question also did not work, as the header file needs a complete declaration of the class to compile. This left me the below implementation, which only works in the cases of a singleton (which was my use case anyway).
The wrapper header file should almost completely duplicate the public interface of the class you want to use.
wrapper.h
namespace foo {
Class Bar() {
public:
void f(int a);
bool g(char* b, int c, bool d);
char* h();
};
}
The wrapper implementation file then creates an instance and passes the calls along.
wrapper.cpp
#include "wrapper.h"
#include "library.h"
namespace foo {
::Bar obj;
void Bar::f(int a) {
return obj.f(a);
}
bool Bar::g(char* b, int c, bool d) {
return obj.g(b, c, d);
}
char* Bar::h() {
return obj.h();
}
}
The main file will interact with only a single instance of the original class, no matter how many times your wrapper class in instantiated.
main.cpp
#include "wrapper.h"
int main() {
foo::Bar obj;
obj.f(1);
obj.g("hello",5,true);
obj.h();
}
Overall, this strikes me as a flawed solution. To fully wrap this class, I think the this could be modified to add a factory class that would be fully contained inside the wrapper implementation file. This class would instantiate the original library class every time your wrapper class is instantiated, and then track these instances. In this way, your wrapper class could keep an index to its associated instance in the factory and bypass the need to have that instance as its own private member. This seemed like a significant amount of work, and I did not attempt to do so, but would look something like the code below. (This probably needs some polish and a real look at its memory usage!)
The wrapper header file adds a constructor & private member to store an instance id
wrapper.h
namespace foo {
Class Bar() {
public:
Bar();
void f(int a);
bool g(char* b, int c, bool d);
char* h();
private:
unsigned int instance;
};
}
The wrapper implementation file then adds a factory class to manage instances of the original library's class
wrapper.cpp
#include "wrapper.h"
#include "library.h"
namespace foo {
class BarFactory {
public:
static unsigned int new() {
instances[count] = new ::Bar();
return count++;
}
static ::Bar* get(unsigned int i) {
return instances[i];
}
private:
BarFactory();
::Bar* instances[MAX_COUNT]
int count;
};
void Bar::Bar() {
instance = BarFactory.new();
}
void Bar::f(int a) {
return BarFactory.get(i)->f(a);
}
bool Bar::g(char* b, int c, bool d) {
return BarFactory.get(i)->g(b, c, d);
}
char* Bar::h() {
return BarFactory.get(i)->h();
}
}
The main file remains unchanged
main.cpp
#include "wrapper.h"
int main() {
foo::bar obj;
obj.f(1);
obj.g("hello",5,true);
obj.h();
}
If all of this seems like a lot of work, then you're thinking the same thing I did. I implemented the basic class wrapper, and realized it wasn't going to work for my use case. And given the hardware limitations of the Arduino, I ultimately decided that rather than add more code to be able to use the HTTPClient implementation in either library, I wrote my own HTTP implementation library in the end, and so used none of the above and saved several hundred kilobytes of memory. But I wanted to share here in case somebody else was looking to answer the same question!
I'm trying to get the benefits of splitting without two files. Split compilation without splitting storage.
I understand the benefits of separating .h and .cpp files, but I really dislike having the files be separate, specifically when the classes are tiny and each file could fit on the same page.
Is there a precompiler option, or perhaps any other trick which would allow me to keep the benefits of separation, while having the text all in the same place? For example:
EDIT: please do not focus too much on this example. It was meant to show off an imaginary pre-processor arg #CPP_SPLIT. The actual code is unimportant, please, please ignore it.
// TinyClass.h
class TinyClass {
TinyClass();
int answerToLife();
}
// the following is a fake compiler arg
// in this example it would be totally unnecessary,
// but many of my classes have some form of circular referencing
// and can not include all the code in the .h file
#CPP_SPLIT
TinyClass::TinyClass() {}
TinyClass::answerToLife() { return 42; }
#CPP_SPLIT_END
I'm not sure it's worth the effort, but you could place the contents of your .cpp file into #ifdef'd sections, like this:
#ifdef PART_ONE
[...]
#endif
#ifdef PART_TWO
[...]
#endif
#ifdef PART_THREE
[...]
#endif
... and then recompile the file over multiple passes, like this:
g++ -DPART_ONE -opart1.o myfile.cpp
g++ -DPART_TWO -opart2.o myfile.cpp
g++ -DPART_THREE -opart3.o myfile.cpp
g++ -o a.out part1.o part2.o part3.o
You can simply put the implementation directly in the header like this:
// TinyClass.h
class TinyClass {
TinyClass() {}
int answerToLife() { return 42; }
};
Also inline might help to do what you want:
// TinyClass.h
class TinyClass {
TinyClass();
int answerToLife();
}
inline TinyClass::TinyClass() {}
inline int TinyClass::answerToLife() { return 42; }
Another potential solution to this appears to be the proposed c++ modules standard. If you happen across this many years down the line, look there.
I am programming on linux using g++ and I often encounter the problem that I need to use a class or data type in a header file which I define later, either at a later point in the header or in another header file.
For instance look at this header file:
class example
{
mydatatype blabla;
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
This will give error because mydatatype is used before its defined
so usually I change it like this:
struct mydatatype; // <-- class prototype
class example
{
mydatatype *blabla; // <-- now a pointer to the data type
// I will allocate the data during runtime with the new operator
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
Now it works. I could often just put the definition above, or include the header which is needed, but I don't want to include headers in a header or juggle with the definition order, it always gets messy.
The solution I showed usually works, but now I have encountered a new phenomenon. This time the datatype is not a class but a typedef, I cant use prototypes for a typedef and I don't want to use the actual datatype which the typedef incorporates.. it's messy too.
Is there any solution to this?
Firstly, the solution you've thought of (prototype and pointer), is unneeded, and slower than just implementing it without the pointer.
The "proper" solution for this, would be creating seperate headers for each type, and then include them in your other header. That way it will always be defined! You can even make them so that they include eachother.
However, if you've ever opened a .h file provided by g++, you've most likely seen this at the start of the header:
#ifndef SOMETHING_H
#define SOMETHING_H
// Code
#endif /* SOMETHING_H */
This is to solve the issue of types redefining themselves.
If they weren't there, and you included the header file multiple times, the types would be redefined, and an error would be thrown. This makes it so that the types are always present, but never included twice.
I hope that helps!
Place each class/type in it's own header file, and then include the relevant header file in other headers where you need it. Use an inclusion guard in each header e.g.:
// SomeHeaderFile.h
#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
// code
#endif
I disagree that this is messy - it allows you have an organised structure to you project, it allows each class to operate independently of others and without worrying about order, and it's a good idea to place each class in it's own file anyway.
You could just define the class inside the other class like
template<class T>
class vertex {
private:
class edge {
public:
vertex<T> *to;
double weight;
edge() {
weight = INFINITY;
to = NULL;
};
} *paths;
T data;
unsigned nof_paths;
public:
vertex(T val) {
data = val;
paths = NULL;
nof_paths = 0;
}
void addPathTo(vertex<T>*&);
edge* getAllPaths() {
return paths;
};
};
Obviously this works for small classes... if your class is ENORMOUS you'll be better using separate header files like the other guys said.
consider a fun.cpp file :
class fun
{
public:
void sum();
void dispaly();
};
Class fun2
{
public:
void subtract();
};
Now consider another c++ file execute.cpp where i want to access only subtract method of fun.cpp file..
i dont want to include "fun.cpp" file into my execute.cpp as it will increase the size(in larger projects)..
so, how can i access any particular method wihtod including the file????
i dont want to include "fun.cpp" file into my execute.cpp
Nor should you, as it would break the one definition rule (assuming the implementations are also in the cpp file).
The usual way to do this is to have the class definition in a header, and include only the header file.
To answer your question, you can, but it's fugly.
C++ allows us to define a class multiple times, as long as the definition is identical. So, in execute.cpp you can simply write:
//execute.cpp
class fun2 //note lower-case 'c'
{
public:
void subtract();
};
// use fun2 here
before you use it. But, again, the usual way is to break the class definition and implementation in a .h file and a .cpp file.
Mandatory advice: read a good introductory C++ book.
You need to include the header file which defines the class fun(and has the declaration of subtract()) in the cpp file where you want to use the function subtract().
Note that the function must be defined though.
fun2.h
#ifndef FUN2_H
#define FUN2_H
Class fun2
{
public:
void subtract();
};
#endif // FUN2_H
fun2.cpp
#include "fun2.h"
void func2::subtract()
{
}
execute.cpp
#include "fun2.h"
//use subtract() through object of `fun2`
Note that, to use a member function in a particular source file, the definition of the class which declares that function should be visible to the compiler, the actual job of linking to the particular definition is done at the linking stage and as long as you follow the above format the linker shall link the appropriate function for you.
Even though you include the file, the linker will only include code that is actually used. This is why using static libraries is sometimes preferable to a dynamic library that has to include everything.
You can't. You need to actually include the file that links to the code that defines the function if you want to include the function. If you just need the interface and aren't going to use the function, you could simply declare the class in execute.cpp as follows
class fun
{
public:
void subtract();
};
But you couldn't use subtract there.
Okay, so this is really werid. I've never encountered anything like this.
Part of my program (Fails to compile) contains three namespaces as following:
// namespaceA.h
namespace A {
enum Kind { jimmy, david };
}
// end of namespaceA.h
// namespaceB.h
#include "namespaceA.h"
namespace B {
class Tree {
public:
Tree *prev;
Tree *next;
Tree *down;
A::Kind kind;
Tree();
~Tree();
};
}
// end of namespaceB.h
// Implementation details of the class are placed in namespaceB.cc
// Constructor / Desctructor defined in the namespaceB.cc file!
// Something like this,
#include "namespaceB.h"
namespace B {
inline Tree::Tree() { ... }
inline Tree::~Tree() { ... }
}
// namespaceC.cc
#include "namespace.B"
namespace C {
void run() {
B::Tree *tree; // FINE
B::Tree tree; // Fail to compile!?
}
}
// end of namespaceC.cc
Now, g++ went along just fine but the linker ld complains:
"namespaceC.cc: undefined reference to `B::Tree::Tree()'
"namespaceC.cc: undefined reference to `B::Tree::~Tree()'
I have never ever encountered anything like this before... This just seems really weird, I don't even know any words/terms to describe this problem.
I would much appreciate any help.
Thanks,
namespaceC.cc: undefined reference to `B::Tree::Tree()'
namespaceC.cc: undefined reference to `B::Tree::~Tree()'
Those are not compiler errors, they are linker errors. The problem is that you declared the constructor and destructor, but never defined them. So the compiler finds the declarations and accepts them, but the linker cannot find the definitions to link the references to.
See this answer for what is a declaration and what is a definition and what they are good/needed for.
Your definitions of B::Tree::Tree() and B::Tree::~Tree() are declared inline. This means they are only available in that source file, not any others.
Either removing inline from the definitions, or moving the inline definitions into a header file included by all source files that need them, should fix the link errors.
You have to write the constructor and destructor for B::Tree somewhere either inline or in namespaceB.cc. By creating an instance of B, you are requiring the existence of the constructor and destructor.
The pointer compiles fine because all pointers are the same. It's just the semantics allowed for different object types differ.
It would have compiled find up until the point you tried to use it.
But to create an actual object, you need the actual definition.
To use definitions from another namespace, you either used scopes, or use using:
#include "namespace.B"
using namespace B;
namespace C {
void run() {
Tree *tree; // FINE
Tree tree; // Fail to compile!?
}
}
or:
#include "namespace.B"
namespace C {
void run() {
B::Tree *tree; // FINE
B::Tree tree; // Fail to compile!?
}
}
You declare the Tree constructor & destructor, but you don't show us where you define them (you just say you implement Tree in namespaceB.cc)
Assuming you have defined them, you must ensure you are including both namespaceC.o and namespaceB.o on your link line.
That's not a namespace problem, neither a compiler error. The compiler is happy, but linker fails to find the definition of B::Tree::Tree(). You need to supply the source file for implementation, or use -c flag to "just compile".
First, you declared constructor and destructor of class Tree yourself so compiler didn't provide default implementation - you need to implement them yourself! (Or just remove those declarations...).
It is not enough to include headers but you need to explicitly say that you're using namespaces from those headers:
In namespaceC.cc add using namespace B; after you include namespace.B or, even better, prepend types with a namespace qualifier:
B::Tree *tree;
B::Tree tree;
I tried the codes in Visual studio 2005. If I remove the "inline" in namespaceB.cc for the constructor and destructor, it can link without errors.
Then I found this post: G++ won't accept inline constructors in C++
it says that for inline functions you must have its definition in every file that calls the function. So it is recommended to put inline definition in header file.