Problems with void function in header of my static library - c++

I'm programming a .lib file for mobile robot.
Among other commands regarding robot movement, I also have command for scanning for Bluetooth devices looking something like:
void ScanForDevices(vector<Device> &Robot)
{
/* code for searching Bluetooth devices and saving their names and addresses into vector of Device struct*/
}
My question is related with writing the header of the .lib file.
One of my commands is:
string RobotMove(int Translation, int Rotation)
{
/* create Command
return string(Command);
}
In the header, for that command I have:
// Returns MOVE command
std::string RobotMove(int Translation, int Rotation);
What I have problem with is what to write in the header for:
void ScanForDevices(vector<Device> &Robot)
I keep getting "Incomplete type is not allowed" is I try to do the same way as RobotMove command. Do I have to declare in some way in the header struct Device?

Do I have to declare in some way in the header struct Device?
If you want to create vectors for Devices, you need to let compiler know the size of the class by defining it. As noted by BoBTFish, the usual way is to just include Device.h header (or similar).
If you use pointers (vector<Device*> or even better, appropriate kind of smart pointer: vector<shared_ptr<Device>>) forward declaration (just stating class Device;) would be enough, as compiler knows size of the pointer on your architecture. (Note that this is completely different approach with different semantics than in your question, and this is just a side-note).

if your header file does not include (directly or indirectly),a definition for vector class you need to add #include <vector> to your header file. The compiler does not know this data type without providing it the right information.

Related

Can I load header(.h) file to get struct at runtime? (C++)

I want to build a C++ program, a Shared Memory Monitor/Interceptor/Recorder/Playbacker.
Basically, I have no problem with those functions I want to implement.
Now my main problem is I want to let this program have ability to load a lot of different ICD file, so I can view different Shared Memory just load that Shared Memory use ICD header file, so I don't need to include that ICD file and re-build this program.
Example ICD Header File A (A.h):
struct StructA
{
bool btState;
float X_Pos;
float Y_Pos;
float Rotate;
};
Example ICD Header File B (B.h):
struct StructB
{
int systemState;
int missionState;
};
So, when my program startup, it will show a File Selector Dialog like many others program, then user can select a Header File, when select done and write this Shared Memory used name to input field, the UI will show about this struct content.
Like(when A.h loaded):
btState false
X_Pos 0.04568f
Y_Pos 456.556f
Rotate 25.258f
So, should I load these file like text file, and build a class to make some string cut/analysis, or use a C++ compiler to compile this file at run-time ?
Tanks.
Header files cannot be replaced at runtime, since they are evaluated at the first step of the compilation of the source code to a fixed binary.
What you are looking for is the factory pattern.
Create a (pure virtual) interface class ICD. This should contain all common data and member functions. From this you can derive the classes A_ICDand B_ICD` (content from your header A and B) .
From given user input you can decide, if you create an object form A_ICD or B_ICD.
The source code using the object of A_ICD or B_ICD uses only the interface class ICD and thus does not need to know, which class is instantiated.
If you actually want a run-time definition of data structure, ANY arbitrary structure, don't use C code. You'd have to parse it on your own or use libraries to parse that and C isn't good for data description. Use domain documents like .xml and a library to parse that, or specialized data-describing languages, e.g OpenDDL.
PS. At work we were solving similar problem as a playback program for network interactions. The program recompilation every time when protocol had changed even slightly would have been unacceptable, but only source of data was indeed a header file used to build communicating programs. A simple parser of struct definitions had been made.
Then program would just remember sizes and offsets of the fields after parsing sequences, making assumptions about memory layout for reading fields one by one out of binary file. It's a highly unportable solution born out of lack of manpower to create intermediate development documentation (protocol documentation in machine-readable form). As it was a network protocol between incompatible platforms, problems of aligning fields and byte order already were solved, with shared memory it would be an existing problem.

error C2027: use of undefined type, with multiple files

I am aware there are multiple questions regarding this problem but none provides a solution under my constraints.
I am working on a project where a header file mips_cpu.h with a certain API is given. I am intended to develope its implementation without altering the header file. This API includes a structure declared in a file mips_cpu.cpp as:
struct mips_cpu_impl;
typedef struct mips_cpu_impl *mips_cpu_h;
I have then defined this structure in mips_cpu.cpp as:
struct mips_cpu_impl{
//Program Counter
uint32_t pc;
uint32_t pcN;
//General Purpose Registers
uint32_t GPReg[32];
//Special registers for MUL / DIV instructions
uint32_t LO;
uint32_t HI;
----- more code ---
};
The problem comes when using this structure in another file mips_cpu_instruction.cpp. When I have this code:
mips_error ADDI(mips_cpu_h state, uint8_t rs, uint8_t rt, uint16_t imm){
uint64_t check = state->GPReg[rs] + imm;
uint32_t tmp = state->GPReg[rs] + imm;
...
more code and appropriate return
}
state then gives the error: use of undefined type 'mips_cpu_imps'
Including the declaration of the structure in the header file solves the problem but I am not supposed to change the header files. Also the header files contain guards, which I dont fullly understand but might be relevant?
The problem is that the file mips_cpu_instruction.cpp doesn't know anything about struct mips_cpu_imps, because it probably includes the .h file that you can't touch (mips_cpu.h), but certainly not the .cpp file where that struct is defined (mips_cpu.cpp). You can add the declaration to mips_cpu_instruction.cpp, but then you'd have a problem if there were other files in the project that use this struct, because you'd have to define it there as well, and when linking you'd get multiple declarations of the same struct.
The best solution would be to add it to the file that you can't modify, but since you can't modify it, you need a workaround. I would create another .h file, using include guards to protect the code from multiple inclusion, and then I would safely #include this new .h file at the top of every .cpp file that needs it. Then it would be defined everywhere, and just once.
In the end, this would mean that to use these APIs you'd have to include 2 .h files: the one you can't touch, and the new one. If you don't want to include 2 files every time, you could even decide to #include mips_cpu.h inside your new file, and then you'd just have to #include the new one, and you could pretty much forget about your unmodifiable file.
Your structure isn't fully defined. It's defined enough for people to use the functions, but not enough to implement the functions. I suspect this is homework and your assignment is to implement these functions, including this structure.
To allow you to get past the programming issue without helping you do your homework directly, put:
struct mips_cpu_impl
{
unsigned GPReg[1];
};
at the top of your mips_cpu_instruction.cpp file, and you'll see these compiler errors go away. You'll need to properly size the array and add whatever other state things you need to model the MIPS core.
p.s. TAs exist for a reason.

Hide class implementation from its interface

I have this code for an interface of a class in a header file and its implementation in a separate source file :
First :The Header file "Gradebook.h"
#include <string>
using namespace std;
class Gradebook{
public:
Gradebook(string);
void setCoursename(string);
string getCoursename();
void displayMessage();
private:
string nameofCourse;
};
Second :The implementation "Gradebook.cpp"
#include "stdafx.h"
#include "Gradebook.h"
#include <iostream>
using namespace std;
Gradebook::Gradebook(string name){
setCoursename(name);
}
void Gradebook::setCoursename(string name){
nameofCourse = name;
}
string Gradebook::getCoursename(){
return nameofCourse;
}
void Gradebook::displayMessage(){
cout << "Display message function shows :" << getCoursename() << endl;
}
how can i link these two separate files in order to use only "Gradebook.h" in other project , and hide my implementation from the client-programmer ?
There are several answers. It would help to know why you actually want to hide the implementation. Here's the reasons why you might want to do this I can think of offhand.
Protecting trade secrets: Forget it. To be able to execute your code, the computer has to be able to run it. Effectively you can strip away comments, method names and variable names by compiling the code as a static library, even run an obfuscator over it to obscure the control flow (at the cost of slowing it down by adding unneeded jumps), but in the end the code (or the machine code generated from it) has to stay sort of readable or it couldn't be executed.
Make it easier to use your code: If you have several source files and might add more files, and you want your clients to just be able to drop in one file to get all the newest changes without having to add individual source files, compile it as a static or dynamic library. Then you can hand someone the library plus the headers and they can just use them.
You can also create an "umbrella header" that includes all the other headers. That way, clients can simply add the path to your library's includes folder to their compiler invocation/project file and include the one header, which includes all others. If you add or split up a header, you just change the umbrella to include the new headers and all projects that use it keep working.
Note that using a library will limit your clients: They can't step through your code in the debugger easily, they can't fix and compile stuff easily. If they need your code to run on a new platform, or want to use different optimization settings in the compiler, they can't just recompile it.
On the other hand if you plan to sell your library, you might want to hold on to your sources. Customers who don't care about the security of having the code if you ever go out of business can get a cheaper version of the library without the source code, you can charge them extra if they want any of the other features by making them buy a version for the new platforms that you coded for them, etc.
Prevent clients from accidentally relying on implementation details: You don't really need to do anything for this except split up your code into public and private files. Usually your implementation file is private and your headers are public, but you may have some private headers for internal classes.
Since C++ does not allow defining instance variables or methods that aren't declared in the header's class declaration like other languages do that support categories or class extensions, you may have to resort to the Private Implementation (aka 'pimpl') pattern.
What this usually means is that you declare one class that defines the public API that simply wraps a pointer to the actual class that contains the real implementation and calls through to it. It usually only has one instance variable, pimpl, which is the pointer to the other class. You simply forward-declare the private class using class Foo; and thus your clients' code doesn't know anything about the private class (unless they explicitly peek into the implementation file or private header, e.g. when fixing a bug).
Create a single-file class I mention this last because it is generally a stupid thing to do, but just in theory, you could also move the implementation file's content into the header. Then clients only need to include the header and get all the sources. This has lots of downsides, though, like making code harder to read, slowing down compile times, and requiring the client to deal with duplicate definitions of the class caused by including the file from several .cpp files. In short: Don't do it.

How to include WinAPI without contaminating the rest of the code?

I'm working on a library in C++ and a part of it is an abstraction layer of several OS functions that i need. I started implementing that with the Windows API but plan to add support for other platforms with #ifdef and such.
What is however starting to become a problem is that including Windows.h propagates to the whole rest of the code where i don't need it and especially, as it is a library, it will also contaminate the code of other people that would use it. I wouldn't really mind if the Windows API used a namespace or some clear way to distinguish its code but instead they #define a lot of pretty common words such as small, near, far (lowercase) and a lot of the function names are also pretty general.
So i would really like if only the platform specific part of my code had access to these and it wouldn't be included anywhere else. I know that the obvious solution would be to only include Windows.h in the CPP files but that isn't always possible because some of the platform specific data types or structures are class member variables such as:
class Window {
public:
// ...
private:
HWND handle;
};
So is there a way to accomplish this?
Thanks.
Use the pimpl idiom ( http://en.wikipedia.org/wiki/Opaque_pointer ). Limitations of the C++ programming language makes it necessary to use tricks like this in order to get information hiding.
One of the ways of doing that is doing it the same way as you would in C (where you don't have that problem at all, because of the following): Forward-declare a struct in the header file and define its contents in the implementation file.
Most people do that by extracting the entire private part of your example into its own struct, whose contents is only defined in the implementation file, and only put a pointer to it in the header file, as the now only member of the private part of the class.
also, #define WIN32_LEAN_AND_MEAN before the #include in order to strip down what the windows.h gives you.

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