Project with external library

In this section we'll develop an app with an external library. External libraries are used in almost every project written in any language. They allow code reuse resulting faster project cycle. We'll learn how to configure an external library with a Code::Blocks project.

We have printed Hello World! text to console. How about printing text in color? We can use a library called conio2 (http://conio.sourceforge.net/) to print text in color and do other text manipulations. A compiled copy of conio2 library is provided together with the book. Consider the following example code:

#include <cstring>
#include "conio2.h"

int main() {
    int screenWidth = 0;
    const char* msg = "Hello World!

";
    struct text_info textInfo;
    inittextinfo();
    gettextinfo(&textInfo);
    screenWidth  = textInfo.screenwidth;
    textcolor(YELLOW);
    textbackground(RED);
    cputsxy( (screenWidth - strlen(msg))/2 , textInfo.cury, const_cast<char*>(msg) );
    textcolor(WHITE); // Restore original colours
    textbackground(BLACK);
    return 0;
}

In this example we have included conio2.h file in second line. This will expose pre-defined functions in conio2 library to our app. We have defined couple of variables namely screenWidth, msg, and textInfo inside main() function. We have then retrieved current console text settings using gettextinfo() function.

In the next line we have saved current screen width to screenWidth variable. Subsequently we have assigned YELLOW foreground color and RED background color. We have used the cputsxy() function to print desired text. We have then restored text colors in the subsequent two lines.

In order to set up external library navigate to Projects | Build options… menu option and click on the Search directories tab as shown in the following screenshot:

Project with external library

Add conio2include path (relative to project path) as shown in the preceding screenshot. We can also use full path if conio2 library is installed in another location. This will instruct compiler to also search this directory for any header files referred in the code.

Next click on the Linker tab as shown in the following screenshot and add the conio2lib relative path as per the following screenshot. This will instruct linker to also search static library in this path.

Project with external library

Click on the Linker settings tab and add libconio.a as per the following screenshot:

Project with external library

After this step is completed our app is ready for compilation. Now compile and run it. We'll see the following output:

Project with external library

Our app is now using an external C/C++ library. We can use other external libraries in a similar manner for our app development.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.36.146