mysql++ compile example Linux Ubuntu 32-bit (a.k.a. example of linking libraries, makefile, headers for C++)

This is more of an exercise in linking libraries and Makefiles than something specific to mysql++, but since I didn't know how to do it before, here goes:

To compile one of the mysql++ examples on my system, I had to specify where the header files were for both the mysqlclient, which I had installed with the apt package manager (see this post), and for mysql++, which I had compiled from source (again, see this post). I also had to specify where the shared object libraries were. The -I option contains the include paths, the -L option contains the shared object paths, and the -l option contains the names of the .so files (excluding the lib and .so component; e.g. -lmysqlpp looks for libmysqlpp.so). On my system, this worked for compilation:
g++ simple1.cpp -I/usr/include/mysql -I/usr/local/include/mysql++ -L/usr/local/lib -L/usr/lib/i386-linux-gnu -lmysqlpp -lmysqlclient -o simple1
And at runtime, the .so files are searched for, so their location needs to be specified. The libmysqlclient.so was installed by the package manager into /usr/lib/i386-linux-gnu and the libmysqlpp.so was installed to /usr/local/lib by default. I ran this and also appended this to my .bashrc file.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/i386-linux-gnu:/usr/local/lib
Once that was working, I moved over to my code. My goal is to learn how to interact with a MySQL database using C++. First I needed to get some basics down, which was simply compiling multiple files since I've evidently forgotten the small amount I knew about C++.

I have 4 to start with:

The main file, stacksToVCF.cpp containing:
#include <stdlib.h>
#include <iostream>
#include "stacksDB.h"
int main ( int argc, char *argv[] )
{
 testcon(argc, argv);
 std::cout << "Hello from main" << std::endl;
 return EXIT_SUCCESS;
} 
stacksDB.h containing
#ifndef  STACKSDB_H_INC
#define  STACKSDB_H_INC

int testcon(int argc, char *argv[]);

#endif 
stacksDB.cpp containing
#include <stdlib.h>
#include <iostream>
#include <mysql++.h>
#include "stacksDB.h"


int testcon (int argc, char *argv[])
{
 mysqlpp::String greeting("Hello from mysqlpp");
 std::cout << greeting << std::endl; 
 return EXIT_SUCCESS;
}
and the Makefile, containing:
CXXFLAGS := -I/usr/include/mysql -I/usr/local/include/mysql++
LDFLAGS := -L/usr/local/lib -L/usr/lib/i386-linux-gnu
LDLIBS := -lmysqlpp -lmysqlclient 
EXECUTABLE := stacksToVCF

all: $(EXECUTABLE)

stacksToVCF: stacksToVCF.o stacksDB.o
        g++ stacksToVCF.o stacksDB.o $(CXXFLAGS) $(LDFLAGS) $(LDLIBS) -o $(EXECUTABLE)

stacksToVCF.o: stacksToVCF.cpp
        g++ -c stacksToVCF.cpp

stacksDB.o: stacksDB.cpp
        g++ -c stacksDB.cpp $(CXXFLAGS) $(LDFLAGS) $(LDLIBS)

clean:
        rm -rf *o $(EXECUTABLE)
This compiles successfully with make and will be the starting point.

Comments