Biicode-logo
  • Explore
  • Plans
  • Learn
    • Get Started
    • Downloads
    • Docs
    • Blog
    • Forum
  • Log in
C/C++ Arduino Raspberry Pi (cross compiling) Node.js
  • Biicode
    • Installation
      • Install Biicode
      • Install C/C++ tools
      • Debian based distributions
      • Arch based distributions
      • Run biicode from source
      • Install C/C++ tools manually
        • Verify your installation
      • Connect through a proxy server
    • Getting started
      • Basics
      • Create your first project
        • [optional] Keeping #includes short
      • Using an IDE
      • Build and run
      • Publishing
    • Dependencies
      • Dependencies
      • Modifying the version you depend on
        • Depending on a block track
    • Publishing
      • Tag a version
      • Private blocks
    • Custom build configuration
      • CMake basics
      • Where is biicode´s “magic”?
      • Define and prepare targets
        • Which source code files are part of the block’s library
        • Choose STATIC or SHARED library
        • Modify which executable targets are made
        • Which source code files are part of each executable
        • Modify which test targets are made
      • Configure targets
        • Configure library target
        • Configure executable target
      • Select build type: Debug or Release
      • Complete variable reference
    • Adapt your library
      • Concepts to understand
        • Key facts
      • Without a previous CMakeLists.txt
        • 1. Look for unresolved dependencies with bii deps
        • 2. Execute bii build
        • 3. Test the libary’s reusability
      • With a previous CMakeLists.txt
        • Option 1: Let biicode do its job in an isolated file
        • Option 2: Build your own target library and link them to BII_LIB_TARGET
        • Option 3: Adapt your CMakeLists.txt filtering files
    • Advanced Usage
      • Custom Layouts
        • Simple Layout
        • TMP Layout
        • Classic Layout
        • CLion Layout
      • Tests
      • Open multiple blocks
        • Working with your own blocks
        • Opening your block
        • Publishing updated code
        • Closing edited block
        • Working with any published block
        • Open a block
        • Publish the changes
        • Close the block
        • Depend on the block you’ve just published
      • Toolchains
      • Override a dependency
        • Override a dependency with block tracks
      • Advanced build configuration
        • Publish, share and reuse CMake scripts
        • Overriding dependencies build options and configuration
      • Publish a block track
        • Publish a new block Track
      • Private blocks
    • Examples
      • Basic Compression Library
        • Simple Huffman Compression - Uncompression
        • Open and build
      • Boost Libraries
        • Boost.Lambda
        • Boost.Coroutine
        • Alternative setup call
        • Extra configuration variables
        • Contribute to the setup scripts
      • Box2D
        • Bounces of a circle falling
        • Open and build
      • C++ challenge
        • Create a new project
        • Copy the code
        • Find and retrieve dependencies
        • Build and run
      • CImg
        • Tron game
        • Open and build
      • Crypto++
        • Encrypt a message
        • Open and build
      • CSparse
        • Read a matrix and solve a linear system
        • Create a new project
        • Open and build
      • cURL
        • HTML page gatherer
        • Open and build
      • Eigen
        • Middle rows from a matrix
        • Open and build
      • Expression Parser
        • Simple form of mathematical expression parsing
        • Open and build
      • fit
        • Tests
      • Flatbuffers
        • Charge a *.fbs file and generate a C++ header
      • Freeglut
        • 1. Create a new project
        • 2. Creating reusable code
        • 3. Find dependencies
        • 4. Build and run
      • GLFW
        • Running the examples
      • GLUI User Interface Library
        • GLUI Window Template
      • Google Mock (GMock)
        • GMock Examples
        • Mocking a simple function
      • Google Test (GTest)
        • Testing a factorial function: Simple test
        • Testing a factorial function: Test suites
        • Open and build
      • HTTP Server
        • How does it work?
        • How can I use it?
        • The code
        • Supported Operating Systems
        • More information
        • List of dependencies
      • json11
        • Simple convert data to json and vice versa
      • json++
        • Simple parser and converter from JSON to XML
      • Miniutf
      • Multivariate Splines
      • libuv
        • Http client/server application
        • Change libuv’s version
      • Little CMS
        • ICC Profile Examples
        • Open and build
      • Log4z
        • Fast stream log strings test
      • lwan Web Server
        • Hello World Example
      • MiLi
      • MuParser
      • OpenCV
        • Showing an image and detecting faces
        • Open and build
      • OpenSSL
        • Encrypting with MD5 and SHA1
        • Develop your project
        • Open and build
      • POCO
        • PDF example
        • Using NetSSL_OpenSSL or NetSSL_Win library
      • PTypes
      • SDL
        • Graphical window interface
        • Open and build
      • SQLite
        • Shopping list database
        • SQLite++ Wrapper
        • Open and build
      • TinyThread++
        • Open and build the examples
        • Simple Hello World with a thread
        • Draw a fractal
      • Zlib
        • Usage example (difficulty: medium)
      • ZMQ
        • Simple client-server with C++ binding
      • ZMQ with Google Protocol Buffers Serialization
    • Integrations
      • Generators and IDEs
        • Eclipse CDT
        • Visual Studio
        • CLion
      • IDEs and VCS
      • Git (GitHub, Bitbucket, etc.)
        • With a new repository
        • Create a block from a git repository
        • Publish from git commit
      • Continuous Integration
        • AppVeyor
        • Travis CI
      • Koding
      • Doxygen
        • Create a Doxyfile template
        • Edit your Doxyfile
        • Generate the Documentation
    • Reference
      • biicode.conf: configure your biicode projects
        • [requirements]
        • [parent]
        • [paths]
        • [dependencies]
        • [mains]
        • [tests]
        • [hooks]
        • [includes]
        • [data]
      • Commands
        • bii build: build your project
        • bii buzz: init, find and build
        • bii clean: delete meta-information
        • bii close: finish editing published blocks
        • bii configure: configure your project
        • bii deps: show block dependencies
        • bii diff: compare block versions
        • bii find: find your external dependencies
        • bii init: creates a new project
        • bii new: creates new blocks
        • bii open: edit published blocks
        • bii publish: publish your blocks
        • bii setup: install necessary tools
        • bii test: test your code
        • bii update: update a block
        • bii user: specify your username
      • Configuration Files
        • layout.bii: define your project layout
        • policies.bii: defining the policies for the code you want to reuse
        • ignore.bii: filtering your files
        • settings.bii: defining your tools and preferences
        • types.bii: configuring non-standard file extensions
    • Release notes
    • FAQs
      • Is biicode free?
      • Is biicode an editor in the cloud?
      • Is biicode a VCS?
      • Can I use biicode with my favourite VCS?
      • Which languages are supported?
      • How does biicode relate to Maven, NPM, PyPI...?
    • Troubleshooting
      • Eclipse projects: “Launch failed. Binary not found” (OS X)
      • g++ doesn’t compile simple code, using thread header
      • Default Build Configuration with bii build not working
  • Arduino
    • Installation
      • Install Biicode
      • Install Arduino tools
      • Install Arduino tools manually
        • Install Arduino SDK manually
    • Getting started
      • Installing biicode and Arduino tools
      • Create your project
      • Define your board
      • Build and upload your program
      • Depending on Fenix Blink
      • Build and upload
    • Arduino commands
      • bii configure -t arduino: configure your project
      • bii build: build your project
      • bii arduino:upload: send your code into the Arduino
      • bii arduino:settings: configure your Arduino settings
      • bii arduino:monitor: start a serial monitor
      • bii configure –toolchain=arduino: enable, disable or change the Arduino cross compilation
    • How to
      • Eclipse IDE configuration
        • How to import your project
        • How to fix “Unresolved inclusion: Arduino.h”
      • Configure your SDK, port and board
        • I changed my Arduino’s port, what happens now?
        • How can I change my Arduino project properties?
        • bii arduino:settings options
      • How to adapt your code
        • 1. Projects with one single .ino file
        • 2. Projects with multiple .ino files
      • How to use the Arduino Yun
        • Download Arduino 1.5
        • Configure your settings
    • Examples
      • Arduino Serial Monitor
        • C++ code
        • Turn ON/OFF one LED
      • Servo and LCD 2x16
        • What do we need?
        • Scheme
        • The code: Display the servo angle into a LCD
        • Build and upload the code
      • Arduino Serial Interface
        • How does it work?
        • How do I use it?
        • C++ code
        • Arduino code
        • Build and run!
    • Troubleshooting
      • Launching Arduino IDE, I get an error ./arduino: 22: ./arduino: java: not found in Ubuntu
  • Raspberry Pi Cross Compilation
    • Installation
      • Install Biicode
      • Install RPI tools
      • Install RPI cross-compiling tools manually
        • C++ tools installation
        • Raspberry Pi tools installation
    • Getting started
      • 1. Installing biicode and C/C++ cross-building tools
      • 2. Create your project
      • 3. Build and run your program (cross-compiling)
      • 4. Send your executable to your Raspberry Pi
      • 5. Depending on WiringPi
    • RPi commands
      • bii rpi:send: send a bin folder
      • bii rpi:settings: configure your Raspberry Pi settings
      • bii rpi:ssh: connect by ssh with the Raspberry Pi
      • bii configure –toolchain=rpi: enable, disable or change the Raspberry Pi cross compilation.
    • How to
      • Installing the biicode package from downloads page is too slow
      • Output selection and volume control
      • Raspberry Pi GPIO Pin Layout
    • Examples
      • WiringPi: C GPIO library
        • How to make a LED blink with Raspberry Pi
        • How to use the RPi PWM output to control a motor
        • How to use softServo to control a Servo
      • HTTP Server: how to control a led by web
        • How can i use it?
      • A funny moving doll with Raspberry PI and biicode
        • You just need paper, scissors, a servo, a Raspberry Pi and biicode!
        • Choose the paper doll you like most
        • Putting it all together!
        • Stick the head to the servo and put the servo in the body
        • Connect the servo to the 5v, GPIO17 and 0v pins
    • Troubleshooting
      • Is it possible to change the version of gcc used for cross-compiling to the Raspberry Pi?
  • Node.js
    • Getting started
      • 1. Installing biicode and node.js
      • 2. Create your project
      • 3. Run your program
      • 4. Depending on redis
    • How to
      • Run your node programs
  • biicode docs
  • Biicode
  • Examples
  • MuParser
  • Edit on GitHub
MiLi
OpenCV

MuParser¶

Many applications require the parsing of mathematical expressions. The main objective of this library is to provide a fast and easy way of doing this. muParser is an extensible high performance math expression parser library written in C++. It works by transforming a mathematical expression into bytecode and precalculating constant parts of the expression. For more information about this library, visit their official website.

You can find here the Muparser library site.

The following example is a math interactive interpreter.

main_muparser.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//---------------------------------------------------------------------------
//
//                 __________                                      
//    _____   __ __\______   \_____  _______  ______  ____ _______ 
//   /     \ |  |  \|     ___/\__  \ \_  __ \/  ___/_/ __ \\_  __ \ 
//  |  Y Y  \|  |  /|    |     / __ \_|  | \/\___ \ \  ___/ |  | \/
//  |__|_|  /|____/ |____|    (____  /|__|  /____  > \___  >|__|   
//        \/                       \/            \/      \/        
//  (C) 2013 Ingo Berg
//
//  example1.cpp - using the parser as a static library
//
//---------------------------------------------------------------------------

#include "ingoberg/muparser/include/muParserTest.h"

#if defined(_WIN32) && defined(_DEBUG)
  #define _CRTDBG_MAP_ALLOC
  #include <stdlib.h>
  #include <crtdbg.h>
  #define CREATE_LEAKAGE_REPORT
#endif

#if defined( USINGDLL ) && defined( _WIN32 )
#error This sample can be used only with STATIC builds of muParser (on win32)
#endif

/** \brief This macro will enable mathematical constants like M_PI. */
#define _USE_MATH_DEFINES		

#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <locale>
#include <limits>
#include <ios> 
#include <iomanip>
#include <numeric>

#include "ingoberg/muparser/include/muParser.h"

using namespace std;
using namespace mu;


#if defined(CREATE_LEAKAGE_REPORT)

// Dumping memory leaks in the destructor of the static guard
// guarantees i won't get false positives from the ParserErrorMsg 
// class wich is a singleton with a static instance.
struct DumpLeaks
{
 ~DumpLeaks()
  {
    _CrtDumpMemoryLeaks();
  }
} static LeakDumper;

#endif

// Forward declarations
void CalcBulk();

// Operator callback functions
value_type Mega(value_type a_fVal) { return a_fVal * 1e6; }
value_type Milli(value_type a_fVal) { return a_fVal / (value_type)1e3; }
value_type Rnd(value_type v) { return v*std::rand()/(value_type)(RAND_MAX+1.0); }
value_type Not(value_type v) { return v==0; }
value_type Add(value_type v1, value_type v2) { return v1+v2; }
value_type Mul(value_type v1, value_type v2) { return v1*v2; }

//---------------------------------------------------------------------------
value_type ThrowAnException(value_type) 
{ 
  throw std::runtime_error("This function does throw an exception.");
}

//---------------------------------------------------------------------------
value_type BulkFun1(int nBulkIdx, int nThreadIdx, value_type v1)
{
  // Note: I'm just doing something with all three parameters to shut 
  // compiler warnings up!
  return nBulkIdx + nThreadIdx + v1;
}

//---------------------------------------------------------------------------
value_type Ping() 
{ 
  mu::console() << "ping\n"; 
  return 0; 
}

//---------------------------------------------------------------------------
value_type StrFun0(const char_type *szMsg) 
{
  if (szMsg) 
    mu::console() << szMsg << std::endl;

  return 999;
}

//---------------------------------------------------------------------------
value_type StrFun2(const char_type *v1, value_type v2,value_type v3) 
{ 
  mu::console() << v1 << std::endl;
  return v2+v3; 
}

//---------------------------------------------------------------------------
value_type Debug(mu::value_type v1, mu::value_type v2) 
{ 
  ParserBase::EnableDebugDump(v1!=0, v2!=0);
  mu::console() << _T("Bytecode dumping ") << ((v1!=0) ? _T("active") : _T("inactive")) << _T("\n");
  return 1; 
}

//---------------------------------------------------------------------------
// Factory function for creating new parser variables
// This could as well be a function performing database queries.
value_type* AddVariable(const char_type *a_szName, void *a_pUserData)
{
  // I don't want dynamic allocation here, so i used this static buffer
  // If you want dynamic allocation you must allocate all variables dynamically
  // in order to delete them later on. Or you find other ways to keep track of 
  // variables that have been created implicitely.
  static value_type afValBuf[100];  
  static int iVal = -1;

  ++iVal;

  mu::console() << _T("Generating new variable \"") 
                << a_szName << std::dec << _T("\" (slots left: ")
                << 99-iVal << _T(")")
                << _T(" User data pointer is:") 
                << std::hex << a_pUserData <<endl;
  afValBuf[iVal] = 0;

  if (iVal>=99)
    throw mu::ParserError( _T("Variable buffer overflow.") );
  else
    return &afValBuf[iVal];
}

int IsHexValue(const char_type *a_szExpr, int *a_iPos, value_type *a_fVal) 
{ 
  if (a_szExpr[1]==0 || (a_szExpr[0]!='0' || a_szExpr[1]!='x') ) 
    return 0;

  unsigned iVal(0);

  // New code based on streams for UNICODE compliance:
  stringstream_type::pos_type nPos(0);
  stringstream_type ss(a_szExpr + 2);
  ss >> std::hex >> iVal;
  nPos = ss.tellg();

  if (nPos==(stringstream_type::pos_type)0)
    return 1;

  *a_iPos += (int)(2 + nPos);
  *a_fVal = (value_type)iVal;

  return 1;
}

//---------------------------------------------------------------------------
void Splash()
{
  mu::console() << _T("                 __________                                       \n");
  mu::console() << _T("    _____   __ __\\______   \\_____  _______  ______  ____ _______\n");
  mu::console() << _T("   /     \\ |  |  \\|     ___/\\__  \\ \\_  __ \\/  ___/_/ __ \\\\_  __ \\ \n");
  mu::console() << _T("  |  Y Y  \\|  |  /|    |     / __ \\_|  | \\/\\___ \\ \\  ___/ |  | \\/ \n");
  mu::console() << _T("  |__|_|  /|____/ |____|    (____  /|__|  /____  > \\___  >|__|    \n");
  mu::console() << _T("        \\/                       \\/            \\/      \\/         \n");
  mu::console() << _T("  Version ") << Parser().GetVersion(pviFULL) << _T("\n");
  mu::console() << _T("  (C) 2013 Ingo Berg\n");
}

//---------------------------------------------------------------------------
value_type SelfTest()
{
  mu::console() << _T( "-----------------------------------------------------------\n");
  mu::console() << _T( "Running test suite:\n\n");

  // Skip the self test if the value type is set to an integer type.
  if (mu::TypeInfo<mu::value_type>::IsInteger())
  {
    mu::console() << _T( "  Test skipped: integer data type are not compatible with the unit test!\n\n");
  }
  else
  {
    mu::Test::ParserTester pt;
    pt.Run();
  }

  return 0;
}

//---------------------------------------------------------------------------
value_type Help()
{
  mu::console() << _T( "-----------------------------------------------------------\n");
  mu::console() << _T( "Commands:\n\n");
  mu::console() << _T( "  list var     - list parser variables\n");
  mu::console() << _T( "  list exprvar - list expression variables\n");
  mu::console() << _T( "  list const   - list all numeric parser constants\n");
  mu::console() << _T( "  opt on       - enable optimizer (default)\n");
  mu::console() << _T( "  opt off      - disable optimizer\n");
  mu::console() << _T( "  locale de    - switch to german locale\n");
  mu::console() << _T( "  locale en    - switch to english locale\n");
  mu::console() << _T( "  locale reset - reset locale\n");
  mu::console() << _T( "  test bulk    - test bulk mode\n");
  mu::console() << _T( "  quit         - exits the parser\n");
  mu::console() << _T( "\nConstants:\n\n");
  mu::console() << _T( "  \"_e\"   2.718281828459045235360287\n");
  mu::console() << _T( "  \"_pi\"  3.141592653589793238462643\n");
  mu::console() << _T( "-----------------------------------------------------------\n");
  return 0;
}

//---------------------------------------------------------------------------
/*
void CheckLocale()
{
  // Local names:
  // "C" - the classic C locale
  // "de_DE" - not for Windows?
  // "en_US" - not for Windows?
  // "German_germany" - For MSVC8
  try
  {
    std::locale loc("German_germany");
    console() << _T("Locale settings:\n");
    console() << _T("  Decimal point:  '") << std::use_facet<numpunct<char_type> >(loc).decimal_point() << _T("'\n"); 
    console() << _T("  Thousands sep:  '") << std::use_facet<numpunct<char_type> >(loc).thousands_sep() << _T("'\n"); 
    console() << _T("  Grouping:       '") << std::use_facet<numpunct<char_type> >(loc).grouping()  << _T("'\n"); 
    console() << _T("  True is named:  '") << std::use_facet<numpunct<char_type> >(loc).truename()  << _T("'\n"); 
    console() << _T("  False is named: '") << std::use_facet<numpunct<char_type> >(loc).falsename() << _T("'\n"); 
    console() << _T("-----------------------------------------------------------\n");
  }
  catch(...)
  {
    console() << _T("Locale settings:\n");
    console() << _T("  invalid locale name\n");
    console() << _T("-----------------------------------------------------------\n");
  }
}

//---------------------------------------------------------------------------
void CheckDiff()
{
  mu::Parser  parser;
  value_type x = 1, 
             v1,
             v2,
             v3,
             eps(pow(std::numeric_limits<value_type>::epsilon(), 0.2));
  parser.DefineVar(_T("x"), &x);
  parser.SetExpr(_T("_e^-x*sin(x)"));
  
  v1 = parser.Diff(&x, 1),
  v2 = parser.Diff(&x, 1, eps);
  v3 = cos((value_type)1.0)/exp((value_type)1) - sin((value_type)1.0)/exp((value_type)1); //-0.110793765307;
  mu::console() << parser.GetExpr() << _T("\n");
  mu::console() << _T("v1 = ") << v1 << _T("; v1-v3 = ") << v1-v3 << _T("\n");
  mu::console() << _T("v2 = ") << v2 << _T("; v2-v3 = ") << v2-v3 << _T("\n");
}
*/

//---------------------------------------------------------------------------
void ListVar(const mu::ParserBase &parser)
{
  // Query the used variables (must be done after calc)
  mu::varmap_type variables = parser.GetVar();
  if (!variables.size())
    return;

  cout << "\nParser variables:\n";
  cout <<   "-----------------\n";
  cout << "Number: " << (int)variables.size() << "\n";
  varmap_type::const_iterator item = variables.begin();
  for (; item!=variables.end(); ++item)
    mu::console() << _T("Name: ") << item->first << _T("   Address: [0x") << item->second << _T("]\n");
}

//---------------------------------------------------------------------------
void ListConst(const mu::ParserBase &parser)
{
  mu::console() << _T("\nParser constants:\n");
  mu::console() << _T("-----------------\n");

  mu::valmap_type cmap = parser.GetConst();
  if (!cmap.size())
  {
    mu::console() << _T("Expression does not contain constants\n");
  }
  else
  {
    valmap_type::const_iterator item = cmap.begin();
    for (; item!=cmap.end(); ++item)
      mu::console() << _T("  ") << item->first << _T(" =  ") << item->second << _T("\n");
  }
}

//---------------------------------------------------------------------------
void ListExprVar(const mu::ParserBase &parser)
{
  string_type sExpr = parser.GetExpr();
  if (sExpr.length()==0)
  {
    cout << _T("Expression string is empty\n");
    return;
  }

  // Query the used variables (must be done after calc)
  mu::console() << _T("\nExpression variables:\n");
  mu::console() <<   _T("---------------------\n");
  mu::console() << _T("Expression: ") << parser.GetExpr() << _T("\n");

  varmap_type variables = parser.GetUsedVar();
  if (!variables.size())
  {
    mu::console() << _T("Expression does not contain variables\n");
  }
  else
  {
    mu::console() << _T("Number: ") << (int)variables.size() << _T("\n");
    mu::varmap_type::const_iterator item = variables.begin();
    for (; item!=variables.end(); ++item)
      mu::console() << _T("Name: ") << item->first << _T("   Address: [0x") << item->second << _T("]\n");
  }
}

//---------------------------------------------------------------------------
/** \brief Check for external keywords.
*/
int CheckKeywords(const mu::char_type *a_szLine, mu::Parser &a_Parser)
{
  string_type sLine(a_szLine);

  if ( sLine == _T("quit") )
  {
    return -1;
  }
  else if ( sLine == _T("list var") )
  {
    ListVar(a_Parser);
    return 1;
  }
  else if ( sLine == _T("opt on") )
  {
    a_Parser.EnableOptimizer(true);
    mu::console() << _T("Optimizer enabled\n");
    return 1;
  }
  else if ( sLine == _T("opt off") )
  {
    a_Parser.EnableOptimizer(false);
    mu::console() << _T("Optimizer disabled\n");
    return 1;
  }
  else if ( sLine == _T("list const") )
  {
    ListConst(a_Parser);
    return 1;
  }
  else if ( sLine == _T("list exprvar") )
  {
    ListExprVar(a_Parser);
    return 1;
  }
  else if ( sLine == _T("list const") )
  {
    ListConst(a_Parser);
    return 1;
  }
  else if ( sLine == _T("locale de") )
  {
    mu::console() << _T("Setting german locale: ArgSep=';' DecSep=',' ThousandsSep='.'\n");
    a_Parser.SetArgSep(';');
    a_Parser.SetDecSep(',');
    a_Parser.SetThousandsSep('.');
    return 1;
  }
  else if ( sLine == _T("locale en") )
  {
    mu::console() << _T("Setting english locale: ArgSep=',' DecSep='.' ThousandsSep=''\n");
    a_Parser.SetArgSep(',');
    a_Parser.SetDecSep('.');
    a_Parser.SetThousandsSep();
    return 1;
  }
  else if ( sLine == _T("locale reset") )
  {
    mu::console() << _T("Resetting locale\n");
    a_Parser.ResetLocale();
    return 1;
  }
  else if ( sLine == _T("test bulk") )
  {
    mu::console() << _T("Testing bulk mode\n");
    CalcBulk();
    return 1;
  }

  return 0;
}

//---------------------------------------------------------------------------
void CalcBulk()
{
  const int nBulkSize = 200;
  value_type *x = new value_type[nBulkSize];
  value_type *y = new value_type[nBulkSize];
  value_type *result = new value_type[nBulkSize];

  try
  {
    for (int i=0; i<nBulkSize; ++i)
    {
      x[i] = i;
      y[i] = (value_type)i/10;
    }
    mu::Parser  parser;
    parser.DefineVar(_T("x"), x);
    parser.DefineVar(_T("y"), y);
    parser.DefineFun(_T("fun1"), BulkFun1);
    parser.SetExpr(_T("fun1(0)+x+y"));
    parser.Eval(result, nBulkSize);

    for (int i=0; i<nBulkSize; ++i)
    {
      mu::console() << _T("Eqn. ") << i << _T(": x=") << x[i] << _T("; y=") << y[i] << _T("; result=") << result[i] << _T("\n");
    }
  }
  catch(...)
  {
    delete [] x;
    delete [] y;
    delete [] result;
    throw;
  }

  delete [] x;
  delete [] y;
  delete [] result;
}

//---------------------------------------------------------------------------
void Calc()
{
  mu::Parser  parser;

  // Change locale settings if necessary
  // function argument separator:   sum(2;3;4) vs. sum(2,3,4)
  // decimal separator:             3,14       vs. 3.14
  // thousands separator:           1000000    vs 1.000.000
//#define USE_GERMAN_LOCALE
#ifdef  USE_GERMAN_LOCALE
  parser.SetArgSep(';');
  parser.SetDecSep(',');
  parser.SetThousandsSep('.');
#else
  // this is the default, so i it's commented:
  //parser.SetArgSep(',');
  //parser.SetDecSep('.');
  //parser.SetThousandsSep('');
#endif

  // Add some variables
  value_type  vVarVal[] = { 1, 2 }; // Values of the parser variables
  parser.DefineVar(_T("a"), &vVarVal[0]);  // Assign Variable names and bind them to the C++ variables
  parser.DefineVar(_T("b"), &vVarVal[1]);
  parser.DefineStrConst(_T("strBuf"), _T("hello world") );
  parser.AddValIdent(IsHexValue);

  // Add user defined unary operators
  parser.DefinePostfixOprt(_T("M"), Mega);
  parser.DefinePostfixOprt(_T("m"), Milli);
  parser.DefineInfixOprt(_T("!"), Not);
  parser.DefineFun(_T("strfun0"), StrFun0);
  parser.DefineFun(_T("strfun2"), StrFun2);
  parser.DefineFun(_T("ping"), Ping);
  parser.DefineFun(_T("rnd"), Rnd);     // Add an unoptimizeable function
  parser.DefineFun(_T("throw"), ThrowAnException);

  
  parser.DefineOprt(_T("add"), Add, 0);
  parser.DefineOprt(_T("mul"), Mul, 1);

  // These are service and debug functions
  parser.DefineFun(_T("debug"), Debug);
  parser.DefineFun(_T("selftest"), SelfTest);
  parser.DefineFun(_T("help"), Help);

#ifdef _DEBUG
//  parser.EnableDebugDump(1, 0);
#endif

  // Define the variable factory
  parser.SetVarFactory(AddVariable, &parser);

  for(;;)
  {
    try
    {
      string_type sLine;
      std::getline(mu::console_in(), sLine);

      switch (CheckKeywords(sLine.c_str(), parser))
      {
      case  0: break;
      case  1: continue;
      case -1: return;
      }

      if (!sLine.length())
        continue;

      parser.SetExpr(sLine);
      mu::console() << std::setprecision(12);

      // There are multiple ways to retrieve the result...
      // 1.) If you know there is only a single return value or in case you only need the last 
      //     result of an expression consisting of comma separated subexpressions you can 
      //     simply use: 
      mu::console() << _T("ans=") << parser.Eval() << _T("\n");

      // 2.) As an alternative you can also retrieve multiple return values using this API:
      int nNum = parser.GetNumResults();
      if (nNum>1)
      {
        mu::console() << _T("Multiple return values detected! Complete list:\n");

        // this is the hard way if you need to retrieve multiple subexpression
        // results
        value_type *v = parser.Eval(nNum);
        mu::console() << std::setprecision(12);
        for (int i=0; i<nNum; ++i)
        {
          mu::console() << v[i] << _T("\n");
        }
      }
    }
    catch(mu::Parser::exception_type &e)
    {
      mu::console() << _T("\nError:\n");
      mu::console() << _T("------\n");
      mu::console() << _T("Message:     ")   << e.GetMsg()   << _T("\n");
      mu::console() << _T("Expression:  \"") << e.GetExpr()  << _T("\"\n");
      mu::console() << _T("Token:       \"") << e.GetToken()    << _T("\"\n");
      mu::console() << _T("Position:    ")   << (int)e.GetPos() << _T("\n");
      mu::console() << _T("Errc:        ")   << std::dec << e.GetCode() << _T("\n");
    }
  } // while running
}

//---------------------------------------------------------------------------
int main(int, char**)
{
  Splash();
  SelfTest();
  Help();

//  CheckLocale();
//  CheckDiff();

  mu::console() << _T("Enter an expression or a command:\n");

  try
  {
    Calc();
  }
  catch(Parser::exception_type &e)
  {
    // Only erros raised during the initialization will end up here
    // formula related errors are treated in Calc()
    console() << _T("Initialization error:  ") << e.GetMsg() << endl;
    console() << _T("aborting...") << endl;
    string_type sBuf;
    console_in() >> sBuf;
  }
  catch(std::exception & /*exc*/)
  {
    // there is no unicode compliant way to query exc.what()
    // so i'll leave it for this example.
    console() << _T("aborting...\n");
  }

  return 0;
}

Create a block and open the example block:

$ bii init my_project
$ cd my_project
$ bii open examples/muparser

The main.cpp file is now in your block. Now you just have to build it and run the executable:

$ bii build
$ cd bin
$ # run executable

You will see next console output after executing the command:

                 __________
    _____   __ __\______   \_____  _______  ______  ____ _______
   /     \ |  |  \|     ___/\__  \ \_  __ \/  ___/_/ __ \\_  __ \
  |  Y Y  \|  |  /|    |     / __ \_|  | \/\___ \ \  ___/ |  | \/
  |__|_|  /|____/ |____|    (____  /|__|  /____  > \___  >|__|
        \/                       \/            \/      \/
  Version 2.2.3 (20121222; SF; 64BIT; RELEASE; ASCII)
  (C) 2013 Ingo Berg
-----------------------------------------------------------
Running test suite:

testing name restriction enforcement...passed
testing syntax engine...passed
testing postfix operators...
  fail: 1000{m} (Unexpected token "1000" found at position 0.)
  fail: 1000 {m} (Unexpected token "1000" found at position 0.)
  fail: f1of1(1000){m} (Unexpected token "1000" found at position 6.)
  fail: -f1of1(1000){m} (Unexpected token "1000" found at position 7.)
  fail: -f1of1(-1000){m} (Unexpected token "1000" found at position 8.)
  fail: f4of4(0,0,0,1000){m} (Unexpected token "1000" found at position 12.)
  fail: 2+(a*1000){m} (Unexpected token "1000" found at position 5.)
  fail: 2*3000meg+2 (Unexpected token "3000meg" found at position 2.)
  failed with 8 errors
testing infix operators...passed
testing variable/constant detection...passed
testing multiarg functions...passed
testing expression samples...passed
testing if-then-else operator...passed
testing member functions...passed
testing binary operators...passed
testing error codes...passed
testing string arguments...passed
Test failed with 8 errors (527 expressions)
-----------------------------------------------------------
Commands:

  list var     - list parser variables
  list exprvar - list expression variables
  list const   - list all numeric parser constants
  opt on       - enable optimizer (default)
  opt off      - disable optimizer
  locale de    - switch to german locale
  locale en    - switch to english locale
  locale reset - reset locale
  test bulk    - test bulk mode
  quit         - exits the parser

Constants:

  "_e"   2.718281828459045235360287
  "_pi"  3.141592653589793238462643
-----------------------------------------------------------
Enter an expression or a command:

You can now start typing mathematical expressions in the console.

Any doubts? Do not hesitate to contact us visit our forum and feel free to ask any questions.

MiLi
OpenCV

© Copyright 2014, biicode.