feelfree February 2016

how to redefine preprocessor directives of c++ libraries in an c++ application program

I give the following example to illustrate my question. Suppose now I am creating a c++ library, and the head file and its implementation file are as follows:

// head.h
class __declspec(dllexport) MyClass
{

    public:
          int obtain_value();

};

// head.cpp
 int MyClass::obtain_value()
{
  #ifndef DEFINE_FIVE
     return 6;
  #else
     return 5;
  #endif

}

In this library, if I define DEFINE_FIVE when compiling the library, I will obtain 5 when invoking obtain_value function; otherwise, I will obtain 6. Let's assume that when I compiled the library, I did not define DEFINE_FIVE. In the c++ program that will call this library, when voking obtain_value function, we expect to have 6. Then my question is, what can I do in the C++ program that invokes the library so that the output of calling this function will be 5. Thanks.

Answers


ul90 February 2016

The preprocessor directives are evaluated at compile time, you cannot change the code in runtime. If you compile the library and DEFINE_FIVE is not defined, the preprocessor will in first pass replace your code to the following:

// head.cpp
int MyClass::obtain_value()
{
     return 6;    
}

As you can see, it will parse and remove all preprocessor directives. Then, the real compiling stage starts with machine code generation.

If you want dynamic values in your library, you have to change your interface, for example:

// head.h
class __declspec(dllexport) MyClass
{

    public:
          int obtain_value(bool give_me_five=false);

};

// head.cpp
 int MyClass::obtain_value(bool give_me_five)
{
     if (!give_me_five)
        return 6;
     else return 5;
}


sunny1304 February 2016

you can use /D switch in visual studio to define DEFINE_FIVE and you will get your desired result.

goto properties --> C/C++ --> preprocessor --> preprocessor definations --> DEFINE_FIVE

the during compile time DEFINE_FIVE will be defined and you will get return 5.


MSalters February 2016

The other answers are perhaps a bit pessimistic. You can create a replacement DLL, which forwards every function to the original DLL except int MyClass::obtain_value(), for which you provide a new implementation.

Downside: direct calls to obtain_value from inside the class won't go through the replacement DLL, which can lead to hard-to-debug errors. This is because you will have two copies of int MyClass::obtain_value() from two DLLs in one process.

Post Status

Asked in February 2016
Viewed 3,417 times
Voted 6
Answered 3 times

Search




Leave an answer