Tag Archive : library

/ library

GMP (GNU Multi Precision) Library is one of vital library in GNU infrastructure. It is a popular library which gives flexibility to operate abritrary precision integers, rationals, and floating point numbers. There are also MPFR (Multi Precision Floating-point Reliably) and MPC (Multi Precision Complex) which are extension to to GMP capability for precision in computation.

In this article we will try to code using GMP, with C, on Linux 64-bit.

Installation

Check whether our box has GMP library.

locate libgmp.a

If GMP is installed already, we will get entry. If not, proceed to GMP site to download and install the library. Just do usual Linux installation procedure.

Getting Start

Before we start, let’s talking about the arbritrary precision. Do we need it? or why do we need it?

Program constitute of two element: algorithm and data. Data is represented by variable, which has size on memory. The size is fix, according to the word size of processor register. To simplify it, computer process numbers in multiple of 2: 8, 16, 32, or 64 bits at a time. For example, if we declare an int variable x, it will have 32 bit size.

Let’s discover by writing little code.

#include <stdio.h>
#include <limits.h>

void printbin(int x)
{
    if (x==0)
        return;
    else
    {
        printbin(x>>1);
        if (x&1)
            printf("1");
        else
            printf("0");
        
    }
}

int main() {
    int k, x, i;
    char c;

    /* 1. Print machine native size and the max/min integer */
    printf("sizeof(int) = %d bits\n", sizeof(int) * 8);
    printf("max(int)    = %d\n", INT_MAX);
    printf("min(int)    = %d\n", INT_MIN);

    /* 2. Try to overflow */
    k = INT_MAX;
    printf("%d + 1 = %d\n", k, k+1);

    /* 3. See the representation of variable */
    printf("Enter x: ");
    scanf("%d", &x);
    printf("x in binary = ");
    printbin(x);
    printf("\n");

    return 0;
}

sizeof(int) gives the number of bytes for integer and INT_MAX is a macro defined in limits.h which inform the largest possible integer. INT_MIN is just the opposite of it.

This is the result in my box.

Selection_056

See the range, -2147483648 (min) to 2147483647 is the valid value of 32-bits integer. If we increment x which hold maximum value it will overflow to negative.

Enter GMP!

Now let’s dive to the GMP. GMP allows us to use integers whose sizes can grow dynamically to the required precision. Imagine it as BigNum, close to. It can support 128, 256, or 1024 bits. There is no need for us to specify this, the library does to dirt. GMP will dynamically allocate memory to accommodate extra bits of precision as we need.

Let’s try it with simple code.

#include <gmp.h>
#include <stdio.h>
 
int main()
{
    char inputStr[1025];
    
    /* type for GMP integers. 
        We don't care about the internal representation 
    */
    mpz_t n;
    int flag;
    
    printf ("Enter your number: ");
    scanf("%1024s" , inputStr);
  
      /* 1. Initialize the number */
    mpz_init(n);
    mpz_set_ui(n,0); 

    /* 2. Parse the input string as a base 10 number */
    flag = mpz_set_str(n,inputStr, 10);
    if (flag == 0)
    {
        printf("Fail");
        return -1;
    }
    
    printf ("n = ");
    mpz_out_str(stdout,10,n);
    printf ("\n");

    /* 3. Add one to the number */
    mpz_add_ui(n,n,1); /* n = n + 1 */

    /* 4. Print the result */
    printf (" n +1 = ");
    mpz_out_str(stdout,10,n);
    printf ("\n");

    /* 5. Square n+1 */
    mpz_mul(n,n,n); /* n = n * n */
    printf (" (n +1)^2 = ");
    mpz_out_str(stdout,10,n);
    printf ("\n");

    /* 6. Clean up the mpz_t handles or else we will leak memory */
    mpz_clear(n);

    return 0; 
}

Remember to include library libgmp.a so GCC won’t complaint. Here is the result:

Selection_057

The complete information is always on GMP manual. But we love simplicity. So here we go.

At minimum we need this skeleton to use GMP.

#include <gmp.h>

/* ... */

  mpz_t n;
  mpz_init(n);

      /* ... */

  mpz_set_ui(n,0);

      /* ... */

  mpz_clear(n);

Now let’s make something out of it. Say, factorial program?

#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>

/* Use iterative solution here. */
void factorial(int n)
{
    int i;
    mpz_t p;
    
    mpz_init_set_ui(p, 1);      /* p = 1 */
    for (i=1; i<= n; i++)
        mpz_mul_ui(p, p, i);    /* p = p * 1 */
    
    printf("%d! = ", n);
    mpz_out_str(stdout, 10, p);
    printf("\n");
    mpz_clear(p);
}

int main()
{
    int n;
    
    do {
        printf("N = ");
        scanf("%d", &n);
    
        if (n <= 1)
        {
            printf("N should be > 1\n");
            printf("Leaving...\n");
            break;
        }
        
        factorial(n);
    } while (1);
    return 0;
}

Try it!

Installing Boost Libraries on Windows

December 9, 2015 | Article | No Comments

Boost library is a set of high-quality libraries that speed up C++ development.

Obtain the Materials

The boost library source code can be downloaded from http://www.boost.org/.

Download and unzip the source code to any path you like.

In the final, we will install Boost library to c:\boostlib so don’t make it as your extracted source code path.

Installation

For Windows, Boost can be used to various toolset. Supported toolset by boost are:

  • borland
  • como
  • gcc
  • gcc-nocygwin
  • intel-win32
  • metrowerks
  • mingw
  • msvc
  • vc7
  • vc8
  • vc9
  • vc10
  • vc11

To build boost libraries, run bootstrap.bat and specify the toolset. For example:

bootstrap.bat mingw

All required files for compilation should be ready. Now you have to define an installation directory and specify a toolset. This toolset is rather different with previous toolset. Here is the list:

  • acc: Hewlett Packard. Only very recent version are known to work well with Boost.
  • borland: borland
  • como: Comeau Computing, Using this toolset may require configuring another toolset to act as its backend
  • darwin: Apple, Appleā€™s version of the GCC toolchain with support for Darwin and MacOS X features such as frameworks.
  • gcc: The Gnu Project, including Cygwin and MinGW
  • hp_cxx: Hewlett Packard, Targeted at the Tru64 operating system.
  • intel: Intel Compiler
  • msvc: Microsoft Visual Compiler
  • sun: Sun, Only very recent versions are known to work well with Boost.
  • vacpp: IBM, The VisualAge C++ compiler.

Here how you do it:

b2 install --prefix=C:/boostlib toolset=gcc

Installing GraphicsMagick on Linux

December 9, 2015 | Article | No Comments

GraphicsMagick is self-claimed as swiss army knife of image processing. It provides a robust and efficient collection of tools and libraries which support reading, writing, and manipulating an image in over 88 major formats including DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

The image processing is multithreaded using OpenMP.

In this article we will discuss about installing ImageMagick in Linux. For this purpose I use:

  1. Slackware64 14.0
  2. gcc

Obtain the Materials

GraphicsMagick can be obtain using two ways: download from sourceforge or clone using Mercurial.

To download the tarball, go to this link. Then, extract the content and change to its directory.

If you want to clone the repository, do this command:

hg clone http://hg.code.sf.net/p/graphicsmagick/code GM
cd GM

At this point, for any method you choose, we are now at GraphicsMagick’s root directory.

Installation

Building ImagesMagick can be done by using following commands (assuming we are at GraphicsMagick’s root directory):

./configure
make
make install

Note that to do installation, you should have enough privilege.

At this point, we have installed GraphicsMagick standard installation.

Installing libHaru from Source

December 9, 2015 | Article | No Comments

LibHaru is a free, cross platform, open source library for generating PDF files. libHaru can be used to produce PDF files, however it still lack at support for reading and editing existing PDF files.

The feature supported by libHaru:

  • Generating PDF files with lines, text, images.
  • Outline, text annotation, link annotation.
  • Compressing document with deflate-decode.
  • Embedding PNG, Jpeg images.
  • Embedding Type1 font and TrueType font.
  • Creating encrypted PDF files.
  • Using various character sets (ISO8859-1~16, MSCP1250~8, KOI8-R).
  • Supporting CJK fonts and encodings. You can add the feature of PDF creation by using HARU without understanding complicated internal structure of PDF. libHaru is written in ANSI C, so theoretically it supports most of the modern OSes.

In this article we will discuss about installing libHaru in Linux. For this purpose I use:

  1. Slackware64 14.0
  2. gcc

Obtain the Materials

libHaru use github to host the codes. To download source codes there are two methods: download as tar ball, or clone the repository.

To download the tarball, go to this link. Then, extract the content and change to its directory.

If you want to clone the repository, do this command:

git clone https://github.com/libharu/libharu.git
cd libharu

At this point, for any method you choose, we are now at libharu root directory.

Installation

libHaru can use cmake for building. To build libHaru, do following

cmake .
make
make install

Note that to do installation, you should have enough privilege.

Introduction to wxWidgets Toolkit

December 9, 2015 | Article | 2 Comments

In beginning it is known as wxWindows.

wxWidgets is a GUI (Graphical User Interface) toolkit and library for creating C++ applications. It is an open source, mature and cross-platform toolkit. wxWidgets applications run on all major OS platforms, Windows, Unix and Mac. The project was started by Julian Smart in 1992. wxWidgets is much more than a toolkit. It provides a large variety of classes for handling streams, databases, threads, online help or application settings. wxWidgets consists of a large group of widgets.

Official site of wxWidget is http://www.wxwidgets.org/

To use tutorial in this site, you should have wxWidget installed. I use wxWidget 2.9.4 mainly and can be downloaded from here http://www.wxwidgets.org/downloads/.

wxWidgets gives you a single, easy-to-use API for writing GUI applications on multiple platforms. Link it with the appropriate library for your platform (Windows/Unix/Mac) and compiler (almost any popular C++ compiler), and your application will adopt the look and feel appropriate to that platform. On top of the great GUI functionality, wxWindows gives you: online help, network programming, streams, clipboard and drag and drop, multithreading, image loading and saving in a variety of popular formats, database support, HTML viewing and printing, and much more.

Who Should Use wxWidgets?

wxWidgets is a framework very much similar to MFC, except for a few negative points of its own. Those MFC programmers who are aware of the growing number of Linux users and who want to write cross platform GUI applications can use wxWidgets. With wxWidgets, it is very easy to use a framework based on C++ and it has a proven record of 13 years. In fact, wxWidgets is very stable and is supported on:

  • Windows 3.1, Windows 95/98, Windows NT, Windows 2000/XP, Windows ME, Windows CE.
  • Linux and other UNIX platforms with GTK+.
  • UNIX with Motif or the free Motif clone Lesstif.
  • Mac OS.
  • Embedded platforms are being investigated. See the wxUniversal project.
  • An OS/2 port is in progress, and you can also compile wxWidgets for GTK+ or Motif on OS/2.

The C++ programming language

The C++ programming language is one of the most widely used programming languages. It is used in many famous desktop applications like MS Office, Macromedia Flash, Firefox, Photoshop or 3D Max. C++ dominates also the world of PC games. It is one of the most difficult programming languages. On the other hand, programming in C++ today is different from programming 10 years ago. There are many tools and libraries that make the programming easier.

For tutorials on C++ programming languages, you can visit here.

Why wxWidgets?

There are a number of options available for writing cross platform GUI development, like: JAVA, Mono.NET, Qt, etc. Java has failed to prove itself as an efficient alternative. Qt is good but commercial and nobody knows its future. Mono.NET seems to be good but is largely driven by Microsoft, it seems like a copy of the work done by Microsoft and it has not yet proved itself as a successful alternative. Also, people would not like to use an extra burden of layer for highly efficient software. As wxWidgets does not use any middle layer and uses only the native controls available on the platform, it gives a nice look and feel to the application.

  • It is very complete. There are many utility classes like : wxRegEx, wxFTP, wxSplashScreen, wxZipInputStream, etc.
  • It is still heavily developed, and has a lot of support from the open source community.
  • Many compilers and platforms are supported : Windows, Linux, Mac, Unix.
  • There’s a lot of documentation available on the internet, forums, wxBook.
  • It’s free for personal and commercial use, and is more flexible than the LGPL license.
  • Whenever possible, wxWindows uses the platform SDK. This means that a program compiled on Windows will have the look and feel of a Windows program, and when compiled on a Linux machine, it will have the look and feel of a Linux program.
  • Ease of learning, it has the same Event tables and similar API and classes like that of WINAPI and MFC.
  • A lot of sample is provided in the samples directory of the installation, which contains how to use the basic controls, multi threading, MDI, drag and drop, sockets, printing and lots more.
  • A lot of ready to use classes are available, like: wxGenericDirCtrl, wxCalendarCtrl, wxDatePickerCtrl, wxTipWindow, wxStyledTextCtrl, wxStaticPicture, wxLEDNumberCtrl, wxEditableListBox, wxFoldPanelBar, wxGIFAnimationCtrl, wxSplashScreen, OGL (Object Graphics Library), FL (Frame Layout), etc. This is one of the main repository.
  • A lot of add on libraries are available to make the programming task more easier:

Main Features

  • Multi threading.
  • Clipboard and drag and drop.
  • Network programming, like: wxSMTP, wxHTTP, wxFTP.
  • Image loading and saving in a variety of popular formats.
  • Streams (ZIP, Network, File, etc.), like: wxRarInputStream.
  • Database support, like: wxDao.
  • HTML viewing and printing, like: wxMozilla, wxIE.
  • XML based resource, multi language/Unicode support.
  • Default style themes available with the OS (e.g.: XP style themes).

Comparison to MFC

MFC and wxWidgets macros

MFC version wxWidgets version
BEGIN_MESSAGE_MAP BEGIN_EVENT_TABLE
END_MESSAGE_MAP END_EVENT_TABLE
DECLARE_DYNAMIC DECLARE_CLASS
DECLARE_DYNCREATE DECLARE_DYMAMIC_CLASS
IMPLEMENT_DYNAMIC IMPLEMENT_CLASS
IMPLEMENT_DYNCREATE IMPLEMENT_DYNAMIC_CLASS
IsKindOf(RUNTIME_CLASS(CWindow)) IsKindOf(CLASSINFO(wxWindow))

MFC and wxWidgets classes

Miscellaneous Classes
MFC version wxWidgets version
CWinApp wxApp
CObject wxObject
CCmdTarget wxEvtHandler
CCommandLineInfo wxCmdLineParser
CMenu wxMenu, wMenuBar, wxMenuItem
CWaitCursor wxBusyCursor
CDataExchange wxValidator
Window Classes
MFC version wxWidgets version
CFrameWnd wxFrame
CMDIFrameWnd wxMDIParentFrame
CMDIChildWnd wxMDIChildFrame
CSplitterWnd wxSplitterWindow
CToolBar wxToolBar
CStatusBar wxStatusBar
CReBar wxCoolBar, but see contrib/src/fl and wxAUI, wxDockIt
CPropertyPage wxPanel
CPropertySheet wxNotebook, wxPropertySheetDialog
Dialog Classes
MFC version wxWidgets version
CDialog wxDialog
CColorDialog wxColourDialog
CFileDialog wxFileDialog
CFindReplaceDialog wxFindReplaceDialog
CFontDialog wxFontDialog
CPageSetupDialog wxPageSetupDialog
CPrintDialog wxPrintDialog
Control Classes
MFC version wxWidgets version
CAnimateCtrl wxMediaCtrl, wxAnimationCtrl
CButton wxButton
CBitmapButton wxBitmapButton
CComboBox wxComboBox, wxChoice
CDateTimeCtrl wxDatePickerCtrl
CEdit wxTextCtrl
CHotKeyCtrl None, but see Keybinder
CListBox, CDragListBox wxListBox
CCheckListBox wxCheckListBox
CListCtrl wxListCtrl, wxListView
CMonthCalCtrl wxCalendarCtrl
CProgressCtrl wxGauge
CReBarCtrl None, but see contrib/src/fl and wxAUI, wxDockIt
CRichEditCtrl wxTextCtrl
CScrollBar wxScrollBar
CSliderCtrl wxSlider
CSpinButtonCtrl wxSpinButton, wxSpinCtrl
CStatic wxStaticText, wxStaticLine, wxStaticBox, wxStaticBitmap
CStatusBarCtrl wxStatusBar
CTabCtrl wxTabCtrl
CToolBarCtrl wxToolBar
CToolTipCtrl wxToolTip
CTreeCtrl wxTreeCtrl
Graphics Classes
MFC version wxWidgets version
CBitmap wxBitmap, wxImage, wxIcon, wxCursor
CBrush wxBrush
CPen wxPen
CFont wxFont
CImageList wxImageList, wxIconBundle
CPalette wxPalette
CRgn wxRegion
CClientDC wxClientDC
CMetaFileDC wxMetaFileDC
CPaintDC wxPaintDC
CWindowDC wxWindowDC
CDC wxDC, wxMemoryDC
Data Structure Classes
MFC version wxWidgets version
CArray, CObArray, CPtrArray wxArray
CStringArray wxArrayString
CDWordArray, CByteArray, CUIntArray wxArrayInt
CList, CPtrList, CObList wxList
CStringList wxArrayString, wxStringList
CMap wxHashMap
CString wxString
CPoint wxPoint
CRect wxRect
CSize wxSize
CTime wxDateTime
CTimeSpan wxTimeSpan, wxDateSpan
COleVariant wxVariant
Internet Classes
MFC version wxWidgets version
CSocket wxSocket
CFtpConnection wxFTP
CHttpConnection wxHTTP
Document/View Classes
MFC version wxWidgets version
CDocument wxDocument
CView wxView
CDocTemplate, CSingleDocTemplate, CMultiDocTemplate wxDocTemplate
Drag and Drop Classes
MFC version wxWidgets version
COleDataSource wxDataObject
COleDropSource wxDropSource
COleDropTarget wxDropTarget
File Classes
MFC version wxWidgets version
CFile wxFile, wxFFile, wxTextFile
CMemFile wxMemoryInputStream, wxMemoryOutputStream
CSocketFile wxSocketInputStream, wxSocketOutputStream
CRecentFileList wxFileHistory
Multithreading Classes
MFC version wxWidgets version
CWinThread wxThread
CCriticalSection wxCriticalSection
CMutex wxMutex
CSemaphore wxSemaphore

Class Hierarchy

A complete hierarchy for library can be sen here.

wxposter

Requirements

Convinced to use wxWidgets?

wxWidgets is cross platform library and currently available on Windows, UNIX, and Mac OS. To make use of wxWidgets, you currently need one of the following setups.

(a) for MS-Windows:

  • A 32-bit or 64-bit PC running MS Windows.
  • A Windows compiler: MS Visual C++ (embedded Visual C++ for wxWinCE port), Borland C++, Watcom C++, Cygwin, MinGW, Digital Mars C++. See install.txt for details about compiler version supported.

(b) for Unix:

  • Almost any C++ compiler, including GNU C++ and many Unix vendors compilers such as Sun CC, HP-UX aCC or SGI mipsPro.
  • Almost any Unix workstation, and one of: GTK+ 2.6 or higher (GTK+ 1.2.10 may still be supported but wxGTK1 port is not maintained any longer and lacks many features of wxGTK2; GTK+ 3 is supported but is still experimental), Motif 1.2 or higher or Lesstif. If using the wxX11 port, no such widget set is required.

(c) for Mac OS/Mac OS X:

  • A PowerPC or Intel Mac running Mac OS X 10.4 or higher
  • The Apple Developer Tools (eg. GNU C++)

Social media & sharing icons powered by UltimatelySocial