Dynamic #define

J

jiuguangw

Hi,

I currently have a application which needs to dynamically define a
function (post-compilation). In Lisp, this can be done by embedding a
function definition inside a string, and call eval(string). In C++, I
thought about using #define macros, like so:

#define some_function() int a = 3; int b = 5; cout << a + b << endl;

int main(int argc, char *argv[]) {
some_function();
return 0;
}

main() in this case would print out "8". The problem is that I don't
know the function definition before hand, and I need something like:

#define some_function() STRING

where STRING contains "int a = 3; int b = 5; cout << a + b <<
endl" (which can be parsed from a file, for example).

Does anyone know how to do this?

Thanks!
 
C

Christopher Pisz

Hi,

I currently have a application which needs to dynamically define a
function (post-compilation).
[snip]

defines are read at pre-compile time and the word dynamic usually means
"changes at runtime", so a dynamic defines are not possible.
It sounds to me that you need to use function pointers or functors
where STRING contains "int a = 3; int b = 5; cout << a + b <<
endl" (which can be parsed from a file, for example).

[snip]

This sounds like you need a factory of functors

Both "design pattern factory" and "C++ functor" can be googled, so I won't
elaborate too much. Hope that helps!
 
J

Jerry Coffin

Hi,

I currently have a application which needs to dynamically define a
function (post-compilation). In Lisp, this can be done by embedding a
function definition inside a string, and call eval(string).

[ ... code elided ]
Does anyone know how to do this?

C++ doesn't provide any direct support for this as part of the language
itself. You have a couple of choices. One is to write a lexer/parser and
evaluate the string yourself. Another that's applicable in some
environments via non-portable code is to invoke the C++ compiler to
create a dynamic library, then dynamically link to that library. The
details of that will depend on your specific environment though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,273
Latest member
DamonShoem

Latest Threads

Top