I am running a simple program:
#include<iostream>
#include<math.h>
using namespace std;
double fu (double x) {
double func = pow(x,0.5);
return func;
}
int main (int argc, char* argv[]) {
double x = 2;
double func = fu(x);
cout<<"f(x) = "<<func<<endl;
return 0;
}
Here func is a function of which value is calculated at x.
Suppose, I need to use this program from another program or if I want to give a function, such as pow(x,0.5) or sqrt(1+sin(x)) during command line running of this program.
How I can do that? If I do it using argv, then can you suggest how can I convert a string into an expression func (that can be evaluated by C++ compiler)?
Any suggestions?
There's no easy way to automatically evaluate that kind of math expressions from a string in c++ (like you may have experienced with kind of eval() expressions in scripting languages).
C++ is a compiled language, and the compiler can't actually resolve anything to concrete function calls and parameter values at compile time.
You have to parse these strings at runtime, break down the input tokens and parameters, and map the parsing results to concrete function calls of the appropriate <cmath> functions applying the parsed parameter values, from within your program.
That's not trivial, and there are a number of solution approaches available. But these completely depend on the kind of math language you want to parse from the command line arguments.
There is not such thing as 'execute an expression in a string' in standard C++. The reason is because C++ is a compiled language (i.e. the output is binary code that the processor can directly execute without any intermediate interpreter). So it cannot just interpret an expression (or code in general) from a string.
I have an implementation in Snap Websites, there is C++ code:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib/snap_expr.cpp
Go here to find the other files:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib
However, instead of implementing an expression parser and execution environment, you may want to make use of an existing library (mine is an example, obviously, actually I have a tool named snapexpr under snapwebsites/src which will do exactly what you are talking about!) In that case you could also choose a different language. For example, Qt offers QScript:
http://qt-project.org/doc/qt-5/qtscript-index.html
In that case, you have to write JavaScript code, but since JavaScript is relatively close to C++, it may work in your environment.
Related
I have a working set of TCL script plus C++ extension but I dont know exactly how it works and how was it compiled. I am using gcc and linux Arch.
It works as follows: when we execute the test.tcl script it will pass some values to an object of a class defined into the C++ extension. Using these values the extension using a macro give some result and print some graphics.
In the test.tcl scrip I have:
#!object
use_namespace myClass
proc simulate {} {
uplevel #0 {
set running 1
for {} {$running} { } {
moveBugs
draw .world.canvas
.statusbar configure -text "t:[tstep]"
}
}
}
set toroidal 1
set nx 100
set ny 100
set mv_dist 4
setup $nx $ny $mv_dist $toroidal
addBugs 100
# size of a grid cell in pixels
set scale 5
myClass.scale 5
The object.cc looks like:
#include //some includes here
MyClass myClass;
make_model(myClass); // --> this is a macro!
The Macro "make_model(myClass)" expands as follows:
namespace myClass_ns { DEFINE_MYLIB_LIBRARY; int TCL_obj_myClass
(mylib::TCL_obj_init(myClass),TCL_obj(mylib::null_TCL_obj,
(std::string)"myClass",myClass),1); };
The Class definition is:
class MyClass:
{
public:
int tstep; //timestep - updated each time moveBugs is called
int scale; //no. pixels used to represent bugs
void setup(TCL_args args) {
int nx=args, ny=args, moveDistance=args;
bool toroidal=args;
Space::setup(nx,ny,moveDistance,toroidal);
}
The whole thing creates a cell-grid with some dots (bugs) moving from one cell to another.
My questions are:
How do the class methods and variables get the script values?
How is possible to have c++ code and compile it without a main function?
What is that macro doing there in the extension and how it works??
Thanks
Whenever a command in Tcl is run, it calls a function that implements that command. That function is written in a language like C or C++, and it is passed in the arguments (either as strings or Tcl_Obj* values). A full extension will also include a function to do the library initialisation; the function (which is external, has C linkage, and which has a name like Foo_Init if your library is foo.dll) does basic setting up tasks like registering the implementation functions as commands, and it's explicit because it takes a reference to the interpreter context that is being initialised.
The implementation functions can do pretty much anything they want, but to return a result they use one of the functions Tcl_SetResult, Tcl_SetObjResult, etc. and they have to return an int containing the relevant exception code. The usual useful ones are TCL_OK (for no exception) and TCL_ERROR (for stuff's gone wrong). This is a C API, so C++ exceptions aren't allowed.
It's possible to use C++ instance methods as command implementations, provided there's a binding function in between. In particular, the function has to get the instance pointer by casting a ClientData value (an alias for void* in reality, remember this is mostly a C API) and then invoking the method on that. It's a small amount of code.
Compiling things is just building a DLL that links against the right library (or libraries, as required). While extensions are usually recommended to link against the stub library, it's not necessary when you're just developing and testing on one machine. But if you're linking against the Tcl DLL, you'd better make sure that the code gets loaded into a tclsh that uses that DLL. Stub libraries get rid of that tight binding, providing pretty strong ABI stability, but are little more work to set up; you need to define the right C macro to turn them on and you need to do an extra API call in your initialisation function.
I assume you already know how to compile and link C++ code. I won't tell you how to do it, but there's bound to be other questions here on Stack Overflow if you need assistance.
Using the code? For an extension, it's basically just:
# Dynamically load the DLL and call the init function
load /path/to/your.dll
# Commands are all present, so use them
NewCommand 3
There are some extra steps later on to turn a DLL into a proper Tcl package, abstracting code that uses the DLL away from the fact that it is exactly that DLL and so on, but they're not something to worry about until you've got things working a lot more.
My software validation group is testing a piece of code like the following:
unsigned int alarm_id;
char alarm_text[16];
static const char text_string[] = "105, Water_Boiling";
signed int arguments_satisfied =
sscanf(text_string,
"%3d, %16s",
&alarm_id, &alarm_text[0]);
if (arguments_satisfied < 2)
{
system_failure();
}
Using the code fragment above, is there a way to get sscanf to return a value greater than 2 without changing the format specifier or changing the arguments to sscanf?
They are exercising the if statement expression, using a unit testing tool.
For C++, are there any differences with the above fragment when compiling as C++?
(We plan to use the same code, but compile as C++.)
FYI, we are using an ARM7 processor with IAR Embedded Workbench.
sscanf returns the number of arguments converted. It cannot convert more arguments than you have told it about. Therefore, unless the format string is changed, sscanf cannot return a value greater than 2. One possible exception -- it may be possible for EOF to be returned if you run out of data before the first argument is converted, but I suspect that only applies to scanf, not sscanf.
For many toolchains (and I'm pretty sure IAR is one), if you have a symbol in an object file and a library, the linker will link to the one in an object file in preference to the one in the library.
So you may be able to provide your own sscanf() function to link during tests and have it return whatever you like.
If the linker has a problem with a symbol conflict between your sscanf() implementation and one in the library, and alternative that may work is to have you unit test sscanf() use a different name (such as unittest_sscanf) and have the build system define a macro to rename sscanf() during the build using something like /Dsscanf=unittest_sscanf for the module under test.
Of course, it may be tricky to make sure that other sscanf() calls that aren't under test don't cause problems.
it is possible in C++ to execute the C++ code from string variable.
Like in Javascript:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
I want something very similar like Javascript in C++. How to do that ?
No, C++ is a static typed, compiled to native binary language.
Although you could use LLVM JIT compilation, compile and link without interrupting the runtime. Should be doable, but it is just not in the domain of C++.
If you want a scripting engine under C++, you could use for example JS - it is by far the fastest dynamic solution out there. Lua, Python, Ruby are OK as well, but typically slower, which may not be a terrible thing considering you are just using it for scripting.
For example, in Qt you can do something like:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QScriptEngine engine;
QScriptValue value = engine.evaluate("var a = 20; var b = 30; a + b");
cout << value.toNumber();
return a.exec();
}
And you will get 50 ;)
You will need to invoke a compiler to compile the code. In addition, you will need to generate some code to wrap the string in a function declaration. Finally, you'll then somehow need to load the compiled code.
If I were doing this (which I would not) I would:
Concatenate a standard wrapper function header around the code
Invoke a compiler via the command line (system()) to build a shared
library (.dll on windows or .so on linux)
Load the shared library and map the function
Invoke the function
This is really not the way you want to write C code in most cases.
Directly, no. But you can:
write that string to a file.
invoke the compiler and compile that file.
execute the resulting binary.
C++ is a compiled language. You compile C++ source into machine code, the executable. That is loaded and executed. The compiler knows about C++ (and has all the library headers available). The executable doesn't, and that is why it cannot turn a string into executable code. You can, indeed, execute the contents of a string if it happens to contain machine code instructions, but that is generally a very bad idea...
That doesn't mean that it wouldn't be possible to do this kind of run-time compilation. Very little (if, indeed, anything) is impossible in C++. But what you'd be doing would be implementing a C++ compiler object... look at other compiler projects before deciding you really want this.
Interpreted languages can do this with ease - they merely have to pass the string to the interpreter that is already running the program. They pay for this kind of flexibility in other regards.
You can use Cling as C++ interpreter.
I created small CMake project for easier Cling integration: C++ as compile-time scripting language (https://github.com/derofim/cling-cmake)
Short answer is no. Hackers would have a field day. You can however use the Windows IActiveScriptSite interface to utilize Java/VB script. Google IActiveScriptSite, there are numerous examples on the web. Or you can do what I am currently doing, roll your own script engine.
Is there a way out to call a function directly from the what the user inputs ?
For example : If the user inputs greet the function named greet is called.
I don't want any cases or comparison for the call to generate.
#include <iostream>
#include<string>
using namespace std;
void nameOfTheFunction(); // prototype
int main() {
string nameOfTheFunction;
getline(cin,nameOfTheFunction); // enter the name of Function
string newString = nameOfTheFunction + "()"; // !!!
cout << newString;
// now call the function nameOfTheFunction
}
void nameOfTheFunction() {
cout << "hello";
}
And is there a concept of generating the function at run time ?
You mean run time function generation ??
NO.
But you can use a map if you already know which all strings a user might give as input (i.e you are limiting the inputs).
For the above you can probably use std::map < std::string, boost::function <... > >
Check boost::function HERE
In short, no this isn't possible. Names in C++ get turned into memory offsets (addresses), and then the names are discarded**. At runtime C++ has no knowledge of the function or method names it's actually running.
** If debug symbols are compiled in, then the symbols are there, but impractical to get access to.
Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval() function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval() in a compiled language such as C++, you have a few options:
Define your own scripting language and write a parser/interpreter for it (lots of work)
Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java
I just want to ask your ideas regarding this matter. For a certain important reason, I must extract/acquire all function names of functions that were called inside a "main()" function of a C source file (ex: main.c).
Example source code:
int main()
{
int a = functionA(); // functionA must be extracted
int b = functionB(); // functionB must be extracted
}
As you know, the only thing that I can use as a marker/sign to identify these function calls are it's parenthesis "()". I've already considered several factors in implementing this function name extraction. These are:
1. functions may have parameters. Ex: functionA(100)
2. Loop operators. Ex: while()
3. Other operators. Ex: if(), else if()
4. Other operator between function calls with no spaces. Ex: functionA()+functionB()
As of this moment I know what you're saying, this is a pain in the $$$... So please share your thoughts and ideas... and bear with me on this one...
Note: this is in C++ language...
You can write a Small C++ parser by combining FLEX (or LEX) and BISON (or YACC).
Take C++'s grammar
Generate a C++ program parser with the mentioned tools
Make that program count the funcion calls you are mentioning
Maybe a little bit too complicated for what you need to do, but it should certainly work. And LEX/YACC are amazing tools!
One option is to write your own C tokenizer (simple: just be careful enough to skip over strings, character constants and comments), and to write a simple parser, which counts the number of {s open, and finds instances of identifier + ( within. However, this won't be 100% correct. The disadvantage of this option is that it's cumbersome to implement preprocessor directives (e.g. #include and #define): there can be a function called from a macro (e.g. getchar) defined in an #include file.
An option that works for 100% is compiling your .c file to an assembly file, e.g. gcc -S file.c, and finding the call instructions in the file.S. A similar option is compiling your .c file to an object file, e.g, gcc -c file.c, generating a disassembly dump with objdump -d file.o, and searching for call instructions.
Another option is finding a parser using Clang / LLVM.
gnu cflow might be helpful