Friedpanseller
Friedpanseller

Reputation: 699

C execute function from different files with the same name

I have 3 AI files that have the same "decideAction(game)" function

In the main file running the game:

In C++ this was easy as I just used namespaces

namespace AI_A {
    #include "AI_A.cpp"
}
namespace AI_B {
    #include "AI_B.cpp"
}
namespace AI_C {
    #include "AI_C.cpp"
}

and in the game I did

if(turn == 0) { AI_A:decideAction(game); } etc....

Is there a way for me to do this for C? Since C doesn't have namespaces or classes?

Each of the AI files have lots of functions in themselves and a decideAction function, so I can't just #include all the AI files and rename decideAction, cos 2 different AI files may have the same function names/global variables.

Thanks!

Upvotes: 0

Views: 654

Answers (1)

bedbad
bedbad

Reputation: 1153

You can't include files like that in C. In C "#include" means a simple file insertion and is done on preprocessor level (like everything that starts with #), so it obviously can not depend on anything runtime(like value of turn)

However, it's not a big deal because you can still use functions from all 3 files simultaneously in many ways. The way that most system work is that they add preprocessor mechanic to names to operate them. Read this: Why doesn't ANSI C have namespaces?

The quick fix I see on preprocessor level is to simply use preprocessor to trick names, which works like a simple find and replace:

#include "AI_A.cpp"
#define decideAction AI_AdecideAction
...
#include "AI_B.cpp"
#define decideAction AI_BdecideAction

Also, don't forget the headers(if any) and watch out for all conflicts, and it will work.

Upvotes: 1

Related Questions