Home > Enterprise >  How to include CPP files that don't exist yet?
How to include CPP files that don't exist yet?

Time:12-08

I have a class Game that serves as an interface, and two classes Poker and BlackJack that implement this interface. I have this method that returns a list of Game objects that I can then use:

#include "Poker.h"
#include "BlackJack.h"
         ...
std::vector<Game*> getGames() {
    std::vector<Game*> gs;
    Game* p = new Poker();
    gs.push_back(p);
    Game* b = new BlackJack();
    gs.push_back(b);
    return gs;
}

At the moment it can only return a list containing these two classes. I want to be able to write more implementations of this interface or get other people's implementations, drop the CPP file in some directory, and be able to call this method, except now with the vector also containing an instance of this new class.

So far I have:

std::string path = "/Games";
std::vector<std::string> filePaths;
for (const auto& file : std::filesystem::directory_iterator(path)) {
    filePaths.push_back(file.path().string());
}

Which creates a list of file paths in some directory.

I have no idea how to continue from here since in order to use these files I would have to add an include statement each time. The end goal is to have a program that users could very easily import their own games onto. How could I go about doing this?

CodePudding user response:

How to include CPP files that don't exist yet?

You cannot. You can only include files that already exist.

In theory, you could achieve what you want using meta-programming. That is: Write a program that writes a header that includes all the headers. Then include the header generated by the meta-program. To update the list, re-run the meta-program. You can automate the build process to do it before compilation.

However, I don't see how it could be a good idea in this case. In order for getGames to change, you would have to change the function anyway. Just add the include directive when you add code that uses the header... Unless you use meta programming to generate the function as well, which could be reasonble. But take into consideration the complexity added by the meta-programming before choosing such design.


The end goal is to have a program that users could very easily import their own games onto.

If the goal is for the users to do this after your program has been compiled, then it won't work at all. You'll need to describe your goal more thoroughly for me to suggest a better approach.


P.S. Avoid the use of bare owning pointers. In this case, I recommend to use std::vector<std::unique_ptr<Game>> instead.

CodePudding user response:

May you consider include a file like gamelist.h? you could generate it when you want to bulid project use Pre-generated events

  • Related