I am trying to print IT SUCCESS\nET SUCCESS\n using following code but it's failing in compilation with error error: ‘printds’ was not declared in this scope which I know is because it's taking macro input as ds literal. Does anyone know how to do this? The use case is that there are several printXX() functions which should be called based on value passed in macro.
#include <stdio.h>
#define FOO(val) { \
print ## val(); \
}
void printIT() { printf("IT SUCCESS\n"); }
void printET() { printf("ET SUCCESS\n"); }
int main() {
const char* ds = "IT", es = "ET";
FOO(ds); FOO(es);
return 0;
}
You can change
FOO(ds); FOO(es);
to
FOO(IT); FOO(ET);
Because macro substitutions happen before your code is compiled.
But you can define a function called FOO like
#include <stdio.h>
#include <iostream>
using namespace std;
void printIT() { printf("IT SUCCESS\n"); }
void printET() { printf("ET SUCCESS\n"); }
void FOO(const string str)
{
if(str=="IT")
printIT();
else
printET();
}
int main()
{
const char* ds = "IT",*es="ET";
FOO(ds);FOO(es);
return 0;
}
it's taking macro input as ds literal.
Yes, that's to be expected. Preprocessor macros are expanded at compile time. The arguments to function-like macros are the literal source-code tokens that appear between the parentheses in the macro invocation. These have no additional meaning to the preprocessor.
Does anyone know how to do this? The use case is that there are several printXX() functions which should be called based on value passed in macro.
Again, macros are expanded, to source code (approximately), at compile time. The process does not and cannot take into account C++ runtime semantics such as converting variables' identifiers into corresponding values.
If runtime dynamic function dispatch based on variables' values is what you're after then you need an altogether different mechanism. You could use ordinary conditional statements to select between different function calls, for example. If you wanted to be even more dynamic then you could consider preparing a lookup table of function pointers, and using that to select and call appropriate functions.
In comments, you added
I've several methods queryServers, queryNodes, queryTargets which I want to call using above trick.
You may be able to accomplish something similar to what you ask via templates or overloaded functions. These mechanisms, too, operate at compile time, so they have no access to runtime information such as variables' values, but they do know about and rely upon C++ data types.
Alternatively, perhaps you're looking for the Strategy pattern.
The first thing you need to know is that the Macros are preprocessor directives which are a fragment of code with a given name. if you use macro name in your program it will replace that code fragment into that place you use the macro name at compile time first stage called Pre-processing stage.
#include <stdio.h>
#define FOO(val) { \
print ## val(); \
}
void printIT() { printf("IT SUCCESS\n"); }
void printET() { printf("ET SUCCESS\n"); }
int main() {
const char* ds = "IT", es = "ET";
FOO(ds); FOO(es);
return 0;
}
In your code, you try to input ds and es variables into FOO function like macro. But ds and es variables declared in program stack only when you run the program. At the compile-time, it just treats them as only texts. Therefore macro function input it takes as text ds and es and replaced with val. That's why you got the compile time error. The following code fragment I have changed is working as you expected.
#include <stdio.h>
#define FOO(val) { \
print ## val(); \
}
void printIT() { printf("IT SUCCESS\n"); }
void printET() { printf("ET SUCCESS\n"); }
int main() {
const char* ds = "IT", *es = "ET";
FOO(IT); FOO(ET);
return 0;
}
If you are interested you can find more about Macros in the following resources.
GCC online documentation and Article about Macros . Also, you can view the preprocessed code using g++ -E (your cpp file name). Thanks.
Possible solution without MACRO:
void printIT() { printf("IT SUCCESS\n"); }
void printET() { printf("ET SUCCESS\n"); }
void foo(std::string_view s)
{
static const std::map<std::string_view, void(*)()> funcs{
{"IT", &printIT},
{"ET", &printET}
};
auto it = funcs.find(s);
if (it != funcs.end()) {
(*it->second)();
}
}
int main() {
const char* ds = "IT";
const char* es = "ET";
foo(ds); foo(es);
}
Demo
Related
How can I use macros as function pointers? I have no idea to solve this. I created a sketch (doesn't work, full of syntax errors) to show what I try to accomplish. Please help!
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation
struct Pin {
CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }
Pin(CalcMethod *calcMethodParam) {
calcMethod = calcMethodParam;
}
int calc(int x) {
return calcMethod(x);
}
};
#define PIN_COUNT 2
Pin *pins[PIN_COUNT];
void start() {
pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
int pin1CalcResult=pins[1]->calc(6); // =6*1024
}
Macros are handled by the preprocessor. They don't exist in the compiled code, therefore there is no pointer.
There is one rule you should follow in modern code and that rule is "don't use macros for furnctions". Macros for functions are a relict that still has some good uses but they are very rare.
Just declare a normal function
int do_out(int x) {
return x / 1024 * 100;
}
Also see "static const" vs "#define" vs "enum"
You can, but not advisable, use macros as named lambdas. Thus
#define D0_OUT [](int x) { return x / 1024 * 100; }
#define D1_OUT [](auto x) { return x * 1024; }
and it should work.
D0_OUT example usable in C++11 and D1_OUT usable with C++14.
I know this is an old thread..
Assuming that you cannot just change the macro to be a function. Maybe it is part of a driver of library somewhere and you need to pass it into another function for some reason like unit testing. You can just wrap the macro within your .c file where you want to use it.
So this:
#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
becomes:
static int D0_OUT_wrapper(int x)
{
return D0_OUT(x);
}
So wrapper goes in like normal:
pins[0] = new Pin(D0_OUT_wrapper);
If you have full control of the code you are writing then just don't use macros.
I was just experimenting with C++. I was trying to write a small macro so that all the functions that I define are automatically stored in a map so that I can query, at run time, what functions exist and run them too. The code is as follows:
#include <map>
using namespace std;
typedef void (*funcPointer)();
map <char*, funcPointer> funcList;
#define Function(x) void x() { funcList[#x] = x;
#define End }
I was used funcPointer and End only for easy readability and implementation. Now, I can define a function as
Function(helloWorld)
cout << "Hello World";
End
Now, to read the function names as a list and run all the functions, I use the following code:
int main() {
//helloWorld();
for (map<char*, funcPointer>::iterator I = funcList.begin(); I != funcList.end(); I++) {
printf(I->first);
I->second();
}
getchar();
return 0;
}
The problem is, if I keep the first line of main() (helloWorld();) commented, the compiler doesn't compile the function and skips it for optimization, as according to the compiler, it is never used. So, the function list turns up empty. If, instead, I call the function once, every thing works perfectly, except that it prints "Hello World" twice. Also, I wrote the macro specifically so I do not have to do that.
So, is there any way that I can force the compiler to compile a function even if it is not used?
The problem is that the code to register the function is inside the function, so won't happen unless you call the function. You might instead register it by initialising a global variable, which will happen automatically before main begins. This might look something like
struct funcRegistration {
funcRegistration(char * name, funcPointer func) {funcList[name] = func;}
};
#define Function(x) \
void x(); \
funcRegistration x##_registration(#x, x); \
void x() {
The compiler compiles the function, however your map won't be populated unless its called.
Because funcList[#x] = x; comes inside the function block { } after macro expansion.
I want to define a macro like
#define AUTO_FUC(x) void x(){}
to define a function named x.
I think the function name will be replaced by x passed by arg x.
AUTO_FUC("test")//it should equal to void test(){} I think
But it didn't.
So how to do this in C++?
I use MinGW and use the macro twice with different args.
AUTO_FUC("A")
AUTO_FUC("B")
It didn't give me function A() and B().Compiler told me void someClass::x() cannot be overloaded.So I know the macro didn't work.
Thanks ,I realize the void "A"() is not a correct function. I forgot I pass a macro as arg and the marco is a string.
And further question. What I really want is create a function with name according to a variable value.And variable value can be write like string a = a;? It should have " am I right? So If I use a string like "A", how can I use the A to create the function void A() when pass the value to marco?
#include <string>
#include <iostream>
#define AUTO_FUC(x) \
void x() \
{\
std::cout<<"hi";\
}\
int main()
{
std::string A = "A";
AUTO_FUC(A); //it's equal to AUTO_FUC("A") it wrong
A(); //So it's undefined;
}
The problem is that you're not passing in A and B (identifiers). You're passing in "A" and "B" (string literals). Macros are textual replacement. So they expand to:
void "A"(){}
void "B"(){}
Surely you'll agree that's not correct C++ code. Change it to this:
AUTO_FUC(A)
AUTO_FUC(B)
[ UPDATE: you've edited your question and now show code where the macro parameters are quoted. Next time, try to post your actual code when asking the question! ;-P ]
Your code works just fine... see it running at ideone.com here
#include <iostream>
#define AUTO_FUC(x) void x(){ std::cout << "hi!\n"; }
AUTO_FUC(test)
int main()
{
test();
}
stdout
hi!
In C/C++, we have the __FUNCTION__ macro which is replaced with a string, holding the name of the current function. But what if I want the function's identifier? That is, not a string, but something I could use as a token to create other identifiers, e.g., if we have
#define MAGIC /* ... */
#define MORE_MAGIC MAGIC ## _bar
void foo() {
printf("%s\n",__FUNCTION__);
MORE_MAGIC();
}
void foo_bar() {
printf("%s\n",__FUNCTION__);
}
void baz() {
printf("%s\n",__FUNCTION__);
MORE_MAGIC();
}
void baz_bar() {
printf("%s\n",__FUNCTION__);
}
int main() {
foo();
}
should print
foo
foo_bar
baz
baz_bar
Notes:
I'm interested in preprocessing-time only.
I would rather not replace my function definitions with a preprocessor call - although I know that would probably work.
Unfortunately you can't. Because you can not unstringify a macro[1].
In other words, you can not remove quotes around the string that generated by __FUNCTION__ and contact it by _bar.
If it's compile-time you want, and for a simple case like your, it might be possible with preprocessor macros and the concatenation operator ##. Maybe something like
#define MORE_MAGIC(f) f##_bar
...
void foo_bar()
{
}
void foo()
{
MORE_MAGIC(foo)();
}
It's not possible to get the name foo automatically though, it has to be explicitly named in the macro "call".
I think the problem is pretty common. You have some input string, and have to call a function depending on the content of the string. Something like a switch() for strings.
Think of command line options.
Currently I am using:
using std::string;
void Myclass::dispatch(string cmd, string args) {
if (cmd == "foo")
cmd_foo(args);
else if (cmd == "bar")
cmd_bar(args);
else if ...
...
else
cmd_default(args);
}
void Myclass::cmd_foo(string args) {
...
}
void Myclass::cmd_bar(string args) {
...
}
and in the header
class Myclass {
void cmd_bar(string args);
void cmd_foo(string args);
}
So every foo and bar I have to repeat four (4!) times. I know I can feed the function pointers and strings to an static array before and do the dispatching in a loop, saving some if...else lines. But is there some macro trickery (or preprocessor abuse, depending on the POV), which makes is possible to somehow define the function and at the same time have it update the array automagically?
So I would have to write it only twice, or possibly once if used inline?
I am looking for a solution in C or C++.
It sounds like you're looking for the Command pattern
Something like this:
Create a map like this
std::map<std::string, Command*> myMap;
then just use your key to execute the command like this....
std::map<std::string, Command*>::iterator it = myMap.find(str);
if( it != myMap.end() ) {
it->second->execute()
}
To register your commands you just do this
myMap["foo"] = new CommandFoo("someArgument");
myMap["bar"] = new CommandBar("anotherArgument");
The basic solution, per my link in the question comment, is to map a string to a function call of some sort.
To actually register the string -> function pointer/functor pair:
Firstly, have a singleton (shock! horror!) dispatcher object.
Let's call it TheDispatcher - it's a wrapper for a map<string,Func>, where
Func is your function pointer or functor type.
Then, have a register class:
struct Register {
Register( comst string & s, Func f ) {
TheDispatcher.Add( s, f );
}
};
Now in your individual compilation units you create
static objects (shock! horror!):
Register r1_( "hello", DoSayHello );
These objects will be created (assuming the code is not in a static library) and will automatically register with TheDispatcher.
And at run-time, you look up strings in TheDispatcher and execute the associated function/functor.
as alternative to the Command pattern you can build an hashtable of string -> function pointers:
typedef void (*cmd)(string);
The ugly macro solution, which you kind-of asked for. Note that it doesn't automatically register, but it does keep some things synchronized, and also will cause compile errors if you only add to mappings, and not the function in the source file.
Mappings.h:
// Note: no fileguard
// The first is the text string of the command,
// the second is the function to be called,
// the third is the description.
UGLY_SUCKER( "foo", cmd_foo, "Utilize foo." );
UGLY_SUCKER( "bar", cmd_bar, "Turn on bar." );
Parser.h:
class Myclass {
...
protected:
// The command functions
#define UGLY_SUCKER( a, b, c ) void b( args )
#include Mappings.h
#undef UGLY_SUCKER
};
Parser.cpp:
void Myclass::dispatch(string cmd, string args) {
if (cmd == "")
// handle empty case
#define UGLY_SUCKER( a, b, c ) else if (cmd == a) b( args )
#include Mappings.h
#undef UGLY_SUCKER
else
cmd_default(args);
}
void Myclass::printOptions() {
#define UGLY_SUCKER( a, b, c ) std::cout << a << \t << c << std::endl
#include Mappings.h
#undef UGLY_SUCKER
}
void Myclass::cmd_foo(string args) {
...
}
You'll have to at least define the functions and add them to some registry. (If they are to be non-inline member functions of some class, you'll also have to declare them.) Other than some domain-specific language generating the actual code (like cjhuitt's macro hackery), I see no way around mentioning these functions two (or three) times.