Monday, August 17, 2015

Setting up log4cpp with CMake

Remember last time when I was writing software application on C programming, this is what I did in diagnosing defects in the application.
#ifdef __DEBUG__
    // logging code here
#endif
This piece is everywhere, trapping malicious bugs. The usage of this piece is like this; If I want the log to show up, I turn on the __DEBUG__ switch like this: #define __DEBUG__, otherwise I'll remove the switch to turn it off.

Looking back my foolish happened in the pass, is a shame. Inspire from JAVA's log4j, I wish I could have something similar thing on C. Yup, there is one called log4cpp and it exists in the world for so long. It has very much similarity to log4j, just that some cautious to take attention during the initial setup.

As I'm using CMake in my project, the installation guide from the site don't have much detail on that. After some try and error, finally I need to have following piece in CMakeLists.txt:
...

include_directories(/usr/local/include/log4cpp)
link_directories(/usr/local/lib/)
find_package(Threads REQUIRED)

target_link_libraries(myprogram liblog4cpp.so ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})

...
The first line is to tell where the log4cpp's header files location, the second line tells where can I load the log4cpp's library. Never though of log4cpp has a dependency on threading library, it requires -pthread option in the build, otherwise following error would be seen:
...

/usr/local/lib/liblog4cpp.so: undefined reference to `pthread_key_create'
/usr/local/lib/liblog4cpp.so: undefined reference to `pthread_getspecific'
/usr/local/lib/liblog4cpp.so: undefined reference to `pthread_key_delete'
/usr/local/lib/liblog4cpp.so: undefined reference to `pthread_setspecific'
Thus, ${CMAKE_THREAD_LIBS_INIT} will do the trick. The last line will wrap up the build and log4cpp is ready to serve.

Goodbye to the ugly code.

No comments: