Labels

Android (1) Apache (1) bash (2) boost (2) C (35) C++ (3) cheatsheet (2) CLion (6) css (3) Debian (33) DL (17) Docker (2) Dreamweaver (2) Eclipse (3) fail2ban (5) git (6) GitHub (5) Hacking (4) html (8) http (1) iOS (1) iPad (1) IRC (1) Java (33) javascript (3) Linux (176) Mac (20) Machine Learning (1) mySQL (52) Netbeans (5) Networking (1) Nexus (1) OpenVMS (6) Oracle (2) Pandas (3) php (17) Postgresql (8) Python (9) raid (1) RedHat (14) Samba (2) Slackware (50) SQL (14) svn (1) tar (1) ThinkPad (1) Virtualbox (4) Visual Basic (2) Visual Studio (1) Windows (3)

Sunday, 19 April 2026

C/C++ linking example using modified cdb file.

 In the following example, we have cdb.cpp and cdb.h


1a) Compile it into an object file: g++ -c cdb.cpp -o cdb.o

1b) If MySQL++ is installed in a non-standard path: g++ -c cdb.cpp -o cdb.o -I/usr/include/mysql++ 

2) Create a static library: ar rcs libcdb.a cdb.o

This gives us:

libcdb.a (a reusable library) and cdb.h (which gets included when needed).

Example usage (main.cpp);

#include "cdb.h"
int main() 
{
    Cdb db;
    db.set_db((char*)"MY_DB");
    if (db.is_connected) 
    {
        std::cout << "Connected!" << std::endl;
    }
    return 0;
}

3a) Compile the above with: 

g++ main.cpp -L. -lcdb -lmysqlpp -o myapp

or sometimes -lmysqlclient is also required:

g++ main.cpp -L. -lcdb -lmysqlpp -lmysqlclient -o myapp 

3b) Alternatively - Compile the above example (main.cpp), without creating a library with:

g++ main.cpp cdb.cpp -lmysqlpp -o myapp

or, again sometimes -lmysqlclient is also required:

g++ main.cpp cdb.cpp -lmysqlpp -lmysqlclient -o myapp


WORKING EXAMPLE

With the following files:

main.cpp - from above.
cdb.cpp - modified from Dalzell source, this version on my GitHub.
cdb.h - modified from Dalzell source, this version on my GitHub.
SimpleIni.h - from Dalzell source (used by cdb,h).
ConvertUTF.h - from Dalzell source (used by SimpleIni.h).


We can build a test with the following (similar to step 3b above):

g++ main.cpp cdb.cpp -I/usr/include/mysql++ -I/usr/include/mysql -L/usr/lib64 -lmysqlpp -lmysqlclient -o myapp

We can test with ./myapp which will probably give a Couldnt find ini file : db.ini 
Note: while the above will test the environment, so further test, this also requires a db.ini file in the same directory, with the following format:

-- Some comment
[MY_DB]
host=192.168.254.198
user=some_user
pass=user_password
dbname=some_db
port=3306

The db.set_db(...) from main.cpp is used to read the settings from this db.ini file, without which we get a Couldnt find ini file : db.ini 

If however we wanted to follow steps 1, 2 & 3a from above and create a library, we would do:
g++ -c cdb.cpp -I/usr/include/mysql++ -I/usr/include/mysql

then create a static library:
ar rcs libcdb.a cdb.o

then to use it: g++ main.cpp -L. -lcdb -lmysqlpp -lmysqlclient -o myapp


TBC

No comments:

Post a Comment

Note: only a member of this blog may post a comment.