Home > OS >  Changing a Macros in another C file
Changing a Macros in another C file

Time:09-06

I have a C file that uses functions defined in another C file. Let's say I am working with main.cpp and func.cpp.

func.cpp

#define SIZE 32

bitset<SIZE> functionA(int a)
{
    Code; 
}

and I have main.cpp

main.cpp

#include "func.cpp"

int main(void)
{
    int a;
    cin >> a;
    bitset<64> out;
    out = functionA(a); /// This is the functionality I want.
}

I don't want to directly change the value of SIZE in func.cpp. I want a way to somehow change the macros definition of SIZE to 64 from main.cpp. After this, I can call functionA and expect it to return a bitset of size 64.

CodePudding user response:

You cannot change the definition of SIZE to be used with bitset<SIZE> without changing func.cpp. It is not possible.

Do not use a macro.

Make functionA a function template:

template <size_t SIZE = 32>
bitset<SIZE> functionA(int a)
{
    Code; 
}

Then in main call it with the SIZE you want:

int main(void)
{
    int a;
    cin >> a;
    bitset<64> out = functionA<64>(a); /// This is the functionality I want.
}

Because 32 is the default for SIZE, whenever you call functionA(x) the returned value is a bitset<32>.

Do not include source files. Source files should not be included. Instead you should compile the source files and then link them. Include a header with the function declaration.

  • Related