Showing posts with label cpp. Show all posts
Showing posts with label cpp. Show all posts

Friday, February 21, 2014

Targeting Windows XP with Visual C++ 2013

Build apps using Visual C++ 2013 that target Windows XP, special steps are needed.

Environment Variables to Set

The following codes is quoted from this blog.

set INCLUDE=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Include;%INCLUDE%
set PATH=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Bin;%PATH%
set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib;%LIB%
set CL=/D_USING_V110_SDK71_;%CL%

For building x64 version, change LIB to this one.

set LIB=%ProgramFiles(x86)%\Microsoft SDKs\Windows\7.1A\Lib\x64;%LIB%

For x86 console/windows applications, set /SUBSYSTEM accordingly:

:: for console application
set LINK=/SUBSYSTEM:CONSOLE,5.01 %LINK%
:: for gui application
set LINK=/SUBSYSTEM:WINDOWS,5.01 %LINK%

For x64 console/windows applications:

:: for console application
set LINK=/SUBSYSTEM:CONSOLE,5.02 %LINK%
:: for gui application
set LINK=/SUBSYSTEM:WINDOWS,5.02 %LINK%

Work with CMake

In CMake there is a WIN32 parameter for add_executable command. It works like this:

add_executable(MyExe WIN32 main.cpp) # this exe will link with /SUBSYSTEM:WINDOWS
add_executable(AnotherExe main.cpp)  # this one will link with /SUBSYSTEM:CONSOLE

When we not target Windows XP, it works correctly. But when we target Windows XP, obviously the link flags are not correct. To fix that, we need add a file to override make rules in CMake. CMAKE_USER_MAKE_RULES_OVERRIDE_CXX is for that purpose.

In your project file, add the following code.

cmake_minimum_required(VERSION 2.8)
set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX your_path/overrides.cmake)

# please make sure the variable is set before the `project` command.
# project(MyApp) 

Then in overrides.cmake, add the following codes.

if(WIN32)
    # if target winxp
    if(TARGETING_XP_64)
        SET(CMAKE_CREATE_WIN32_EXE /SUBSYSTEM:WINDOWS,5.02)
        SET(CMAKE_CREATE_CONSOLE_EXE /SUBSYSTEM:CONSOLE,5.02)
    elif(TARGETING_XP)
        SET(CMAKE_CREATE_WIN32_EXE /SUBSYSTEM:WINDOWS,5.01)
        SET(CMAKE_CREATE_CONSOLE_EXE /SUBSYSTEM:CONSOLE,5.01)
    endif()
endif()

Now, to build targetting Windows XP, you could run cmake like the folowing.

cmake -G "YourGenerator" -DTARGETING_XP=On path_to_your_project.cmake

And the following for XP x64.

cmake -G "YourGenerator" -DTARGETING_XP_64=On path_to_your_project.cmake

Tuesday, February 18, 2014

Core Dump on Ubuntu

Listed below are just several notes about core dump on Ubuntu.

The location of core dump files

The following command can print out where will the core dump files be placed.

cat /proc/sys/kernel/core_pattern

If the output start with a | character, the kernel then will write the core dump to the stdin of the command after the | character.

Core dump file size

The following command can remove core dump file size limit.

ulimit -c unlimited

Apport

On ubuntu, core dump files are forwarded to Apport by default. So if you can’t find the core file in your current directory, you may want to try /var/crash. Probably you will see crash report files there.

The command apport-unpack can be used to extract the core files out of a crash report files.

Friday, February 14, 2014

RPATH on Windows

On Linux, we can specify shared library search paths for our executable/libraries using RPATH. On Windows, however, there is no such easy way to do that. A possible solution is to use /DELAYLOAD and SetDllDirectory.

Ways to Load a DLL

Basically speaking, there are three ways to load a DLL on windows.
- Implicitly loading. In this way, we link our application against the .lib file of the DLL. The DLL will be loaded once the application was invoked.
- Explicitly loading. That is the way we call LoadLibrary Win32 API to load a DLL. The search path can be changed by calling SetDllDirectory function.
- Delayed loading. Similar to Implicit loading, but the DLL won’t be loaded until once of functions in it got called.

Delay loading

/DELAYLOAD is a linker option of MSVC compiler (version 6 or later) that can tell the linker which DLL we want to delay load. So, to simulate the functionality of RPATH, we can specify the DLL should be delay loaded via /DELAYLOAD at link time, and call SetDllDirectory function to set the search path. After that, there are three ways to force load the library.

  • We can simply call a function that is exported in that library to force loading the library.
  • Call LoadLibrary to explicitly load the library.
  • Call __HrLoadAllImportsForDll to force load the library.

Listed below is an example to use the above method to delay load a DLL. Please note that to make the code work, delayimp.lib should be linked against.

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <delayimp.h>
#include <string>

bool loadTheLibraryNow(const char* dir) {
    const char* baseDllName = "library-to-delay-load.dll";

    if (!dir)
        return false;

    // backup current dll directory
    char previousDllDirectory[MAX_PATH] = { '\0' };
    if (!::GetDllDirectoryA(MAX_PATH, previousDllDirectory)) {
        previousDllDirectory[0] = '\0';
    }

    // set new current dll directory to
    if (!::SetDllDirectoryA(dir))
        return false;

    // force load the dll
    bool result = SUCCEEDED(__HrLoadAllImportsForDll(baseDllName));

    // restore the dll directory to old value
    ::SetDllDirectoryA(previousDllDirectory);

    return result;
}

Please See here for more details.

Thursday, February 13, 2014

Test If a Type Has a Member Function

Sometimes we want to handle types with some specific member functions specially. The followin examples shows how to do that using SFINAE and enable_if.

#include <iostream>
#include <type_traits>

using namespace std;

// SFINAE test
template<typename T>
class has_test {
    template<typename U, U> class check {};
    template<typename C> static char f(check<void(C::*)(int), &C::test>*);
    template<typename C> static long f(...);
public:
    static const bool value = (sizeof(f<T>(nullptr)) == sizeof(char));
};

template<typename T>
std::enable_if_t<has_test<T>::value, void> test(T& t) {
    cout << typeid(T).name() << " has a 'test' member function. " << endl;
}

template<typename T>
std::enable_if_t<!has_test<T>::value, void> test(T& t) {
    cout << typeid(T).name() << " has no 'test' member function. " << endl;
}

struct A {
    void test(int) {}
};

struct B {
};

int main() {
    A a;
    B b;
    test(a);
    test(b);
}

Here is the output of the program.

struct A has a 'test' member function. 
struct B has no 'test' member function. 

Wednesday, January 29, 2014

Koenig Lookup and Stream Operator

Today I met with a wired problem with my C++ code. It tooks me several hours to fix it and it turns out it is related to Koeing Lookup and Name Hidding.

Problem

Here is the sample code that has problem.

#include <iostream>

namespace A {
    struct Foo { int data; };
}

namespace B {
    template<typename T>
    void output(const T& t) { std::cout << t; }

    struct Bar { int data; };
    std::ostream& operator<< (std::ostream& stream, const Bar& bar) {
        return stream << bar.data; 
    }
}

std::ostream& operator<< (std::ostream& stream, const A::Foo& foo) {
    return stream << foo.data; 
}

int main() {
    A::Foo foo;
    B::output(foo);
}

I got the following compilation error with it. Basially the compiler complains that it can’t find the operator<<(std::ostream&, const A::Foo&) function.

c:\path\main.cpp:9: error: C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const A::Foo' (or there is no acceptable conversion)

Solution

The fix is simply moving operator<<(std::ostream&, const A::Foo&) into namespace A.

Why?

Listed below are why the error occurs, and why the fix works.

Basically speaking, when C++ compiler tries to find an unqualified function, it will search in two different ways:

  • A: Search the namespacs from the one where the function is called up to the global namespace (also take into account of using namespace and using) until found.
    • For example, in the sample code, it will search for the operator<<(std::ostream&, const A::Foo&) function both B and global namespaces.
  • B: Koenig lookup - search in the set of associated namespaces of all its argument types.

    • For example, in the sample code, it will search for the operator<<(std::ostream&, const A::Foo&) function in the following two namespaces:

      • std, the namespace of the first argument type ostream
      • A, the namespace of the second argument Foo
    • Here is the definition on Wikipedia of Koenig Lookup.

      In the C++ programming language, argument-dependent lookup (ADL), or argument-dependent name lookup, applies to the lookup of an unqualified function name depending on the types of the arguments given to the function call.

In the sample code, since the function operator<<(std::ostream&, const A::Foo&) can be found using method A, then it should work. But it does not!!!

The problem is that there is already a function operator<< in namespace B. Though it has different signature from the one we are looking for, compiler simply stop searching up. That is why the function can’t be found. Basically, it is because of Name Hiding.

The reason why the fix works is that once we move the function into namespace A, then it can be found using method B. So basically it is because of Koenig Lookup.

Monday, January 27, 2014

STL documentation in QtCreator

The post shows how to enable STL documentation in QtCreator.

  • Go to http://en.cppreference.com/w/Cppreference:Archives and download the latest Qt help book
  • Extract the .qtc file out of the achive downloaded
  • Open QtCreator, go to Tools -> Options -> Help -> Documentation tab
  • Click Add button and select the .qtc file
  • Restart QtCreator

That’s it. You could now move your cursor to a STL keyword and press F1 to view its documentation.

Friday, January 24, 2014

Example to Use Boost.Log

The following code is an example that illustrates how to use Boost.Log.

Several Notes:

  • In the example, debug_output_backend (e.g. DebugView, or Visual Studio Output Pane) is used. It support multi-process logging. It is only available on Windows. On linux, syslog_backend is a good alternative.
  • Log level control is implemented using a global varable g_log_level and a boost log filter function log_level_filter.
  • Messages can be logged by send them to log streams, e.g. LOG(), LOG_ERROR.
  • All the items that output to log stream should support operator<<(std::ostream&) or operator<<(boost::log::record_ostream&)

See also Boost.Log

#include <iostream>
#include <iomanip>
#include <string>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/sinks/debug_output_backend.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/phoenix/bind/bind_function_object.hpp>
#include <boost/log/support/date_time.hpp>

using namespace std;
using namespace boost;
using namespace boost::log;

namespace {

    // log severity level
    enum log_level {
        Debug,
        Info,
        Warning,
        Error
    };

    // logger type with severity level and multithread support
    typedef sources::severity_logger_mt<log_level> logger_t;

    // windows debugger output (e.g. DbgView) sink type with synchronization support
    typedef sinks::synchronous_sink<sinks::debug_output_backend> sink_t;

    // global variables
    log_level g_log_level = Info;  // log level
    logger_t* g_logger; // logger

    // define the keywords to use in filter and formatter
    BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", log_level)
    BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", 
        attributes::local_clock::value_type)
    BOOST_LOG_ATTRIBUTE_KEYWORD(processid, "ProcessID", 
        attributes::current_process_id::value_type)
    BOOST_LOG_ATTRIBUTE_KEYWORD(threadid, "ThreadID", 
        attributes::current_thread_id::value_type)

    // the filter used to filter log records according to level
    bool log_level_filter(value_ref<log_level, tag::severity> const& level) {
        return level >= g_log_level;
    }

    // stream output support for log_level
    std::ostream& operator<<(std::ostream& stream, log_level level) {
        static const char* strings[] = { "debug", " info", " warn", "error" };
        int l = static_cast<size_t>(level);
        if (l >= 0 && l < sizeof(strings) / sizeof(strings[0]))
            stream << strings[l];
        else
            stream << l;
        return stream;
    }

    void initialize_logger() {
        // create a logger
        g_logger = new logger_t();

        boost::shared_ptr<core> core = core::get();

        // add attributes
        core->add_global_attribute("TimeStamp", attributes::local_clock());
        core->add_global_attribute("ProcessID", attributes::current_process_id());
        core->add_global_attribute("ThreadID", attributes::current_thread_id());

        // add level filter
        core->set_filter(phoenix::bind(&log_level_filter, severity.or_none()));

        // create a debug output sink
        boost::shared_ptr<sink_t> sink(new sink_t());

        // sink formatter
        sink->set_formatter(expressions::stream
            << "[" << processid << "]"
            << "[" << threadid << "]"
            << "[" << expressions::format_date_time(
                                        timestamp, "%Y-%m-%d %H:%M:%S") << "]"
            << "[" << severity << "] "
            << expressions::smessage);

        // add sink
        core->add_sink(sink);
    }

    void cleanup_logger() {
        if (g_logger) {
            delete g_logger;
            g_logger = nullptr;
        }
    }

    // macros to get log streams
    #define LOG_DEBUG()     BOOST_LOG_STREAM_SEV(*g_logger, Debug) \ 
        << __FUNCTION__ << "(): "
    #define LOG_INFO()      BOOST_LOG_STREAM_SEV(*g_logger, Info) \ 
        << __FUNCTION__ << "(): "
    #define LOG_WARNING()   BOOST_LOG_STREAM_SEV(*g_logger, Info) \ 
        << __FUNCTION__ << "(): "
    #define LOG_ERROR()     BOOST_LOG_STREAM_SEV(*g_logger, Error) \ 
        << __FUNCTION__ << "(): "
    #define LOG()           LOG_INFO()
}

void doSomething() {
    LOG() << "Log message from doSomethng()";
}

int main(int argc, char** argv) {
    initialize_logger();

    LOG() << "Application started";
    LOG_ERROR() << "An error occured";
    doSomething();

    LOG_DEBUG() << "This message won't be log if g_log_level >= Info";
    g_log_level = Debug;
    LOG_DEBUG() << "This message will be log if g_log_level >= Debug";

    cleanup_logger();
    return 0;
}

Sunday, January 19, 2014

Build Qt 5.2 with Visual C++ 2013

Prerequisites

Steps

  • Extract Qt Source to c:\build\qt-everywhere-opensource-src-5.2.0
  • Extract ICU to c:\build\icu
  • Setup Visual C++ Environment
  • Add Python, Ruby, Perl to PATH
  • Add GnuWin32 to PATH
    set PATH=%PATH%;c:\build\qt-everywhere-opensource-src-5.2.0\gnuwin32\bin

  • Add ICU to INLCUDE, LIB, PATH
    set INCLUDE=%INCLUDE%;c:\build\icu\inlcude
    set LIB=%LIB%;c:\build\icu\lib
    set PATH=%PATH%;c:\build\icu\lib

  • Configure
    configure -platform win32-msvc2013 -release -shared -c++11 -opensource -confirm-license -nomake tests -nomake examples -make-tool jom

  • Build
    jom

Friday, January 3, 2014

Thursday, January 2, 2014

Qt5 DEPENDPATH Breaking Changes

Today when trying to build an old project with Qt5, I got a lot of warning and errors like the one below.

WARNING: Failure to find: foo.cpp
...
Error: dependent 'foo.cpp' does not exist.

The warnings and errors are about the lines in a foo.pri file.

INCLUDEPATH += $$PWD
DEPENDPATH += $$PWD
HEADERS += foo.h
SOURCES += foo.cpp

In my project, foo.pri exists in the same directory of foo.cpp and foo.h. With Qt4, wherever the foo.pri is included, the foo.cpp and foo.h will be added to source file list and header file list respectfully.

But obviously this won’t work with Qt5. After some googling, I found this post. Basically there is breaking changes of DEPENDPATH in qmake that shipped with Qt5.

Though it is far from being an elegant solution, the following lines fix the issue.

INCLUDEPATH += $$PWD
HEADERS += $$PWD/foo.h
SOURCES += $$PWD/foo.cpp

Monday, December 30, 2013

Floating Point Binary Representation in C++

Interested in how a float point number is stored in memory? The following C++ code can print it out.

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    float f = 3.14159;
    bitset<32> bs(*(int*)&f);
    cout << bs << endl;
}

The output is 01000000010010010000111111010000.