Project structure in C++ in relation to publicly exposed headers - c++

I am trying to understand project structure in c++, I am finding it difficult to get my head around class structure and header files.
Extract from article 1 (linked at bottom of this post)
By convention, include directory is for header files, but modern practice > suggests that include directory must strictly contain headers that need
to be exposed publicly.
My first question of this process is with regards to a separate class file that is within the include directory.
What is purpose of exposing your headers?
Following on from this, looking at an example of an exposed header file. Linked in the following GH repo: https://github.com/AakashMallik/sample_cmake
How does the Game_Interface class relate back to the Game_Engine?
game_interface.h
#pragma once
#include <game_engine.h>
class GameInterface
{
private:
GameEngine *game;
public:
GameInterface(int length);
void play(int num);
};
I have looked else where for a simple explanation of this process but, all I have found so far is nothing that can be understood in the context of this example.
Fairly new to C++ background in web technologies.
Link to article 1: https://medium.com/heuristics/c-application-development-part-1-project-structure-454b00f9eddc

What is purpose of exposing your headers?
Sometimes you may be developing some functionality or a library. You might want to help some other person or customer or client by sharing the functionality of your code. But you don't want to share the exact working details.
So for instance you wish to share an Image processing functionality which applies beautiful filters to it. But at the same time you don't want them to exactly know how did you implement it. for such scenarios, you can create a header file, say img_filter.h having function declaration -
bool ApplyFilter(const string & image_path);
Now you can implement entire details in img_filter.cpp:
bool ApplyFilter(const string & image_path)
{
....
// Implementation detail
...
}
Next you can prepare a dll of this file which could be used by your client. For reference of working, parameters, usage etc. you can share the img_filter.h.
Relation with Interface:
A well defined interface is generally nice to have so you can change implementation details transparently, which means, that HOW you implement the details don't matter as long as the interface or the function name and parameters are kept intact.

Related

load config file for game, singleton or passing down the tree or anything else?

I'm trying to create simple game in C++. At one point I want to have some setting, save and load from config file.
The config file should be read from the beginning, and should be accessible anywhere it needed.
So far I only see Singleton pattern as a solution.
Another way is to create an object an pass it down, but it can mess
up the current code.
I've also search and found something called Dependency Injection.
Is dependency injection useful in C++
Which design patterns can be applied to the configuration settings problem?
But I don't quite understand it, you still have to create an object in main and pass it down, right?
Singleton is quite simple, but some consider it antipattern, while pass it down the tree can mess up my current code. Is there any other Patterns?
P/S: I'm also curious how games load their setting.
I would suggest something simple as the following example, which circumvents any singleton-related or initialization order issue:
struct global_state
{
config _config;
};
struct game_state
{
global_state& _global_state;
};
int main()
{
global_state globals{load_config_from_file()};
game_state game{globals};
game.run();
}
Since _global_state is a member of game_state, it can be used in member functions without the need of explicitly passing it as a parameter:
void game_state::update_ui()
{
const float text_size = _global_state._config.get_float("text_size");
_some_text.set_size(text_size);
}

C++ - Using a variable without knowing what it is called

I have a program that uses plug-ins. As I'm in development, these plug-ins are currently just .h and .cpp files that I add or remove from my project before re-compiling, but eventually they will be libraries.
Each plug-in contains lists of data in vectors, and I need to dynamically load data from the plug-ins without knowing which plug-ins are present. For instance:
// plugin1.h
extern vector<int> plugin1Data;
// plugin2.h
extern vector<int> plugin2Data;
// main.cpp
vector<vector<int>> pluginDataList;
int CountPlugins () {
// Some function that counts how many plug-ins are present, got this bit covered ;)
}
int main() {
int numPlugins = CountPlugins();
for (int i = 0; i < numPlugins; i++) {
vector<int> newPluginData = /***WAY TO ADD PLUGIN DATA!!!***/;
pluginDataList.push_back(newPluginData);
}
}
I already access the names of each plugin present during my CountPlugins() function, and have a list of names, so my first gut feeling was to use the name from each plugin to create a variable name like:
vector<string> pluginNames = /*filled by CountPlugins*/;
string pluginDataName = pluginNames.at(i) + "Data";
// Use pluginDataName to locate plugin1Data or plugin2Data
That's something I've done before in c# when I used to mess around with unity, but I've read a few stackoverflow posts clearly stating that it's not possible in c++. It's also a fairly messy solution in C# anyway as far as I remember.
If each plugin was a class instead of just a group of vectors, I could access the specific data doing something like plugin2.data... but then I still need to be able to reference the object stored within each plugin, and that'll mean that when I get round to compiling the plugins as libraries, I'll always have to link to class declaration and definition, which isn't ideal (though not out of the question if it'll give a nicer solution over all).
I'm all out of ideas after that, any help you can offer will be most welcome!
Thanks! Pete
Why dont you save the data as JSON between the application and the plugins ? That way you will also allow other types of tech to plug-into your app, like javascript based plugins via an embedded version of v8 or c#/.net plugins via mono.'

C++ class for managing the access to database

The question is more a Best way of doing question than a real problem.
Context and what I'm doing
I have an application that must access to the database. Therefore I have a class DatabaseManager that is called every time I need to access the database and which does for instance:
DatabaseManager *db = new DatabaseManager;
std::vector<Element> elementVector = db->getAElementsById(id);
And you the same for all insert, update or remove requests.
What eventually happened...
...is that my file has already 1200 lines and is growing with every new feature.
The question
So how do pretty people do ?
One header several splitted files? (This told that it's not a good idea)
Splitting the class in several class? The databaseManager is one class, it would be a nonsense...
Is there any other option? (I'm not familiar with the notion of namespace, maybe is it a way?)
I read also other post but didn't find either the good question to ask google, or people answering my question.
I have my database module split into more than one file. For example, one file handles insertions, another file handles extractions and a third handles searches.
Mine is actually more complex, but the practice should be to split up the code into separate themed files, preferably no more than 300 LOC (Lines Of Code).
The solution I chose for now is the following (because I was too lazy to reconstruct new classes and so on) : I splitted the class in several cpp files
// DatabaseManager.h
class DatabaseManager
{
//// Getters - in DatabaseManager_getters.cpp
public:
// Movies
Movie getOneMovieById(const int id);
QList<Movie> getAllMovies(const QString fieldOrder = "title");
....
private:
// Other functions for getters
Movie hydrateMovie(QSqlQuery &query);
//// Inserts - in DatabaseManager_insert.cpp
public:
bool insertNewMovie(Movie &movie);
....
private:
bool insertNewTag(Tag &tag);
....
//// Updates - in DatabaseManager_update.cpp
public:
bool updateMovie(Movie &movie);
....
//// Delete - in DatabaseManager_delete.cpp
public:
bool deleteMovie(Movie &movie);
private:
bool deletePeople(const People &people);
};
And obviously the .cpp files are following what announced. It's easier for me to find where a function is and to maintain the code.
Another time, I'll think twice if it's not more relevant to follow the advices you gave.
Thx again !

In the .cpp, is there a way to auto-implement all the functions from its .h?

I think this would increase the quality of life when devving, but google came up with nothing and I couldn't find anything specific inside inside Netbeans either.
What I want is to start with this header:
class bla
{
public:
static void gfg(somearg asd);
};
Then I open the blank bla.cpp and pressed 'autoimplement'. After that, it would look like this:
#include "bla.h"
static void bla::gfg(somearg asd)
{
//TODO: implement
throw unimplemented("void bla::gfg(somearg) is unimplemented");
}
Anyone know of a tool like this?
I found http://www.radwin.org/michael/projects/stubgen/
"stubgen is a C++ development tool that keeps code files in sync with their associated headers. When it finds a member function declaration in a header file that doesn't have a corresponding implementation, it creates an empty skeleton with descriptive comment headers."
This looks like it does exactly what you want it to do.
Some time has passed and in the meantime the requested feature seems to have been implemented in netbeans. Refer to https://netbeans.org/bugzilla/show_bug.cgi?id=213811 , which also gives a description on how to use it:
Note:
Implemented CTRL+SPACE.
IDE suggest implementing of class method if CTRL+SPACE was pressed:
- inside file that already has at least one method definition
- between method declarations

Managed C++ - Importing different DLLs based on configuration file

I am currently writing an application that will serve a similar purpose for multiple clients, but requires adaptations to how it will handle the data it is feed. In essence it will serve the same purpose, but hand out data totally differently.
So I decided to prodeed like this:
-Make common engine library that will hold the common functionalities of all ways and present the default interface ensuring that the different engines will respond the same way.
-Write a specific engine for each way of functioning....each one compiles into its own .dll.
So my project will end up with a bunch of libraries with some looking like this:
project_engine_base.dll
project_engine_way1.dll
project_engine_way2.dll
Now in the configuration file that we use for the user preferences there will an engine section so that we may decide which engine to use:
[ENGINE]
Way1
So somewhere in the code we will want to do:
If (this->M_ENGINE == "Way1")
//load dll for way1
Else If (this->M_ENGINE == "Way2")
//load dll for way2
Else
//no engines selected...tell user to modify settings and restart application
The question is...How will I import my dll(s) this way? Is it even possible? If not can I get some suggestions on how to achieve a similar way of functioning?
I am aware I could just import all of the dlls right at the start and just choose which engine to use, but the idea was that I didn't want to import too many engines for nothing and waste resources and we didn't want to have to ship all of those dlls to our customers. One customer will use one engine another will use a different one. Some of our customer will use more than one possibly hence the reason why I wanted to externalize this and allow our users to use a configuration file for engine switching.
Any ideas?
EDIT:
Just realized that even though each of my engine would present the same interface if they are loaded dynamically at runtime and not all referenced in the project, my project would not compile. So I don't have a choice but to include them all in my project don't I?
That also means they all have to be shipped to my customers. The settings in the configuration would only dictate with class I would use to initialize my engine member.
OR
I could have each of these engines be compiled to the same name. Only import one dll in my main project and that particular engine would be used all the time. That would render my customers unable to use our application for multiple clients of their own. Unless they were willing to manually switch dlls. Yuck
Any suggestions?
EDIT #2:
At this point seeing my options, I could also juste make one big dll containing the base engine as well as all the child ones and my configuration to let the user chose. Instead of referencing multiple dlls and shipping them all. Just have one huge one and ship/reference that one only. I am not too fond of this either as it means shipping one big dll to all of my customers instead of just one or two small ones that suit there needs. This is still the best solution that I've come up with though.
I am still looking for better suggestions or answers to my original question.
Thanks.
Use separate DLLs for each engine and use LoadLibrary in your main project to load the specific engine based on the configuration.
Have your engine interface in some common header file that all engines will derive from and this interface will be used in your main project aswell.
It might look like this:
// this should be an abstract class
class engine {
public:
virtual void func1() = 0;
virtual void func2() = 0;
...
};
In each different engine implementation export a function from the DLL, something like this:
// might aswell use auto_ptr here
engine* getEngine() { return new EngineImplementationNumberOne(); }
Now in your main project simply load the DLL you're interested in using LoadLibrary and then GetProcAddress the getEngine function.
string dllname;
if (this->M_ENGINE == "Way1")
dllname = "dllname1.dll";
else if (this->M_ENGINE == "Way2")
dllname = "dllname2.dll";
else
throw configuration_error();
HMODULE h = LoadLibraryA(dllname.c_str());
typedef engine* (*TCreateEngine)();
TCreateEngine func = (TCreateEngine)GetProcAddress(h, "getEngine");
engine* e = func();
The name of the exported function will probably get mangled, so you could either use DEF files or extern "C" in your DLLs, also don't forget to check for errors.
The solution I came to is the following:
Engine_Base^ engine_for_app;
Assembly^ SampleAssembly;
Type^ engineType;
if (this->M_ENGINE == "A")
{
SampleAssembly = Assembly::LoadFrom("path\\Engine_A.dll");
engineType = SampleAssembly->GetType("Engine_A");
engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2));
}
else
{
SampleAssembly = Assembly::LoadFrom("path\\Engine_B.dll");
engineType = SampleAssembly->GetType("Engine_B");
engine_for_app = static_cast<Engine_Base^>(Activator::CreateInstance(engineType, param1, param2, param3, param4));
}
I used the answer from Daniel and the comments that were made on his answer. After some extra research I came across the LoadFrom method.