gotakk
gotakk

Reputation: 41

Different different version of same code

I developed a small soft, that just uploads files to one provider. The provider can be set before compilation.

Actually I have three same projects (with same code) but with three different provider. To illustrate, I have copied two times the folder project and modified only the source code relative to the provider.

I search a solution to join to the same project and just set a "variable" to choose the provider at the compilation

I thought to create a #define PROVIDER, with provider = [ S3 | YOUTUBE | FTP ], and then to write in code

#ifdef S3
provider = new S3Provider();
#elif YOUTUBE
provider = new YoutubeProvider();
#else
provider = new FtpProvider();
#endif

This solution is a bit ugly and I don't know other ways

Can you help me please ? Thank you !

Upvotes: 2

Views: 125

Answers (3)

You might use some configuration file (perhaps located in a well defined place by default, like ~/.myprogconf on Linux) and have your program parse it and use some generic (HTTP & FTP client) library (such as libcurl) later.

Upvotes: 1

g24l
g24l

Reputation: 3145

The only safe way that you want to do it is by using typedef

typedef PROVIDER_TYPE provider_type;

provider =  new provider_type();

compile with g++ -DPROVIDER_TYPE=S3 to get S3

Now, you cannot get non-sensical case as g++ -DPROVIDER_TYPE=x -DPROVIDER_TYPE=y because you will get very nice pre-processor errors.

Even better you can put that in a header file and completely drop the base class provider because you could do:

provider_type * provider = new provider_type();

Upvotes: 1

ams
ams

Reputation: 25599

If you want conditional compilation then preprocessor defines are the way to do it, although you can pass the values in on the command line instead of writing it into the source.

#if defined(USE_S3)
provider = new S3Provider();
#elif defined(USE_YOUTUBE)
provider = new YoutubeProvider();
#elif defined(USE_FTP)
provider = new FtpProvider();
#else
#error You must specify a provider!
#endif

And compile with

c++ -DUSE_S3 blah.cc

Note that you can't use -DPROVIDER=S3 because #if does not allow string comparison.


An alternative solution is to name the provider class on the command line:

#ifndef PROVIDER
#error You must specify a provider!
#endif

provider = new PROVIDER ();  // The space before () is important!

and then compile with

c++ -DPROVIDER=S3Provider

I prefer the first one because it better documents that three providers are implemented.

Upvotes: 1

Related Questions