Tag: c++

Entries for tag "c++", ordered from most recent. Entry count: 113.

Pages: 1 2 3 ... 15 >

21:03
Sun
02
Mar 2014

Using Google Test in Visual C++ 2012

I was recently learning Google Test (Google C++ Testing Framework). It's a C++ library from Google (shared under new BSD license) to do unit testing, following xUnit convention.

As always with any library in C++, it's not that easy as just download the sources, compile and use it. Here are my experiences with making it work in Visual C++ 2012:

1. Visual Studio solution is already prepared in msvc/gtest.sln. You just need to confirm upgrading to new version and ignore report with warnings.

2. You only need "gtest" project. It compiles a static library. That's the way I decided to use it. Alternatively you could just include all library sources to your project.

3. The library uses tuple from new C++ that requires variadic templates. Visual C++ doesn't support this feature, so to make it compiling without errors, you need to globally define following macros (in project properties > C/C++ > Preprocessor > Preprocessor Definitions, in both Debug and Release configurations, in both library and your client project):

GTEST_USE_OWN_TR1_TUPLE=0
_VARIADIC_MAX=10

4. If your project uses different way of linking to the standard library than gtest, you will get linker errors like:

1>gtestd.lib(gtest-all.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in MyTestApp.obj
1>msvcprtd.lib(MSVCP110D.dll) : error LNK2005: "public: __thiscall std::_Container_base12::_Container_base12(void)" (??0_Container_base12@std@@QAE@XZ) already defined in gtestd.lib(gtest-all.obj)
1>msvcprtd.lib(MSVCP110D.dll) : error LNK2005: "public: __thiscall std::_Container_base12::~_Container_base12(void)" (??1_Container_base12@std@@QAE@XZ) already defined in gtestd.lib(gtest-all.obj)
...

That's probable as default setting for new project is to link it dynamically, while gtest project links it statically. It should be same in both gtest and your project. To change it to linking dynamically, enter project properties > C/C++ > Code Generation > Runtime Library and choose Multi-threaded Debug DLL (for Debug) and Multi-threaded DLL (for Release).

After setting it up, usage of the library is very easy. You just need in your project:

1. Add "include" subdirectory to include directories.
2. #include <gtest/gtest.h>
3. Link with "msvc/gtest/Debug/gtestd.lib" (in Debug) and "msvc/gtest/Release/gtest.lib" (in Release).
4. Write your tests, like:

TEST(IntegerTest, Addition)
{
    EXPECT_EQ(4, 2 + 2);
    EXPECT_EQ(10, 3 + 7);
}

5. Write main function:

int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

I like this library - it's easy to learn and use while quite powerful. It's also well documented - the main documentation is: Primer, Advanced Guide, FAQ.

There is also a GUI application available, called Guitar (Google Unit Test Application Runner) or gtest-gbar, which allows running your testing application and browsing results in a window instead of console.

Comments (3) | Tags: c++ libraries testing | Author: Adam Sawicki | Share

21:04
Fri
17
Jan 2014

CppDepend 4 Pro for Free

It looks that they've just released a new major version of CppDepend - great static code analysis tool for C++. What's New in CppDepend 4 page lists several improvements. What is more important though is that they've decided to give away Pro license for free to open source C/C++ contributors. They say:

To apply for this free license, Please make sure that you meet the following criteria:

I think it's worth trying to apply for that. See also my review of CppDepend.

Comments (7) | Tags: tools c++ | Author: Adam Sawicki | Share

22:21
Wed
02
Oct 2013

Time Measurement in Game Programming - My Article in ProgramistaMag

In new issue 9/2013 (16) of Programista magazine there is my next article (in Polish) - "Pomiar czasu w programowaniu gier" (Time Measurement in Game Programming). This is an article about very specific subject, important in game development, as well as programming other real-time systems. Most books about game development mention the subject of time measurement, but usually go quickly to higher level like creating some timer class etc. This article focuses on lower level and gives solid theoretical background. It covers:

Plus some other information... You can find the magazine e.g. in Empik stores, as well as subscribe for electronic or paper version.

Comments (10) | Tags: productions c++ | Author: Adam Sawicki | Share

19:58
Mon
05
Aug 2013

Smart Pointers in C++11 - My Article in ProgramistaMag

In new issue 7/2013 (14) of Programista magazine there is my next article (in Polish) - "Inteligentne wskaźniki w C++11" (Smart Pointers in C++11). This is a long one. In this article I introduce the problem of manual memory management in C++ along with the concept of object lifetime and the matter of object ownership. I then describe RAII idiom and explain what smart pointer mean. I describe features of smart pointer classes available in C++11 standard library (auto_ptr, unique_ptr, shared_ptr, weak_ptr) and show how to use them with short examples. I also touch some additional topics like writing custom deleters and show source code of custom implementation of a simple smart pointer.

You can find the magazine e.g. in Empik stores, as well as subscribe for electronic or paper version.

Comments (5) | Tags: productions c++ | Author: Adam Sawicki | Share

19:25
Sat
27
Apr 2013

Writing Efficient C++ Code - my Article in ProgramistaMag

I started cooperation with Programista - Polish magazine for programmers and other IT professionals. You can find my first article in the latest issue 4/2013 (11).

My article - "Writing Efficient C++ Code" - is about achieving best possible efficiency of native C++ code. It describes data-oriented design as an alternative to pure object-oriented philosophy and shows its advantages, mostly related to consciously designed layout of data in memory, which makes good use of CPU cache. It also mentions operations that should be avoided if code is to be efficient, shows some language tricks and Visual C++ project options that help with generating efficient code and mentions parallelization.

Besides, in each issue of the magazine you can find interesting articles about different programming languages, libraries and technologies, as well as interviews, book reviews and other articles related to software development. The magazine is available for subscription in electronic and paper form.

Comments (3) | Tags: productions c++ optimization | Author: Adam Sawicki | Share

19:14
Tue
23
Apr 2013

Type Visualization in Visual Studio 2012 Debugger

When you code in C++ and you have your own library of data types, especially containers, it would be nice to be able to see it in the debugger formatted in some readable way. In Visual C++/Visual Studio, there used to be a special file autoexp.dat designed for this purpose, as described in "Writing custom visualizers for Visual Studio 2005". But it had weird syntax and poor error reporting.

Now in Visual Studio 2012 there is a new way of defining debugger visualizations for native data types, called Native Type Visualization Framework (natvis). All you need to do is to create an XML file with ".natvis" extension following special format and place it in directory: %USERPROFILE%\Documents\Visual Studio 2012\Visualizers. Full documentation of this format is on this single MSDN page: "Creating custom views of native objects in the debugger". See also "Expressions in Native C++" and "Format Specifiers in C++".

For example, if you have a singly linked list:

template<typename T>
class CLinkedList {
   // ...
    struct CNode {
       T Value;
       CNode* Next;
    };
    size_t Count;
    CNode* Head;
};

Default visualization of a 3-element object in the debugger would look like this:

But if you create following natvis file:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
   <Type Name="CLinkedList&lt;*&gt;">
       <DisplayString>{{Count = {Count}}}</DisplayString>
       <Expand>
           <Item Name="[Count]">Count</Item>
           <LinkedListItems>
               <Size>Count</Size>
               <HeadPointer>Head</HeadPointer>
               <NextPointer>Next</NextPointer>
               <ValueNode>Value</ValueNode>
           </LinkedListItems>
       </Expand>
   </Type>
</AutoVisualizer>

Next time you start debugging (restarting Visual Studio is not required), same object will be shown as:

Besides extracting single fields from objects, evaluating whole C++ expressions and formatting values into a string for summary of whole object, this framework is able to visualize following data structures:

Comments (3) | Tags: visual studio debugger c++ | Author: Adam Sawicki | Share

18:16
Sun
25
Nov 2012

C++ is Good for Fast Coding

Many people believe that C and C++ are languages suitable only for coding some special kinds of applications - low level or high performance. I think it's not 100% true. Here is a story: 2011-11-11 we had a game development competition organized in this topic on forum.warsztat.gd, called "Explosive Hamster Exhibition Compo". The name comes from crazy game titles that can be generated by Video Game Name Generator, which was used in this compo to generate a topic, unique for each participant. We had to develop a game in 3 hours. From 3 topics generated for me I chose "Micro Sewer Plus" and made a game about closing sewers. (Download: Reg - MicroSewerPlus.7z - binary + source code, 479 KB.)

I managed to write this simple yet playable game in 3 hours and took 2nd place out of 10, despite my game was written in C++, while many others used the "easier" or "quicker" technologies like Java, JavaScript, XNA o Game Maker. What I want to show here is that C++ is not necessarily a language in which coding is hard and slow. It's all about having a good framework - a library with a set of functions and classes that handles all low-level stuff and allows you to implement the game itself quickly, easily and directly as you think about it. You don't have to manually free all allocated memory if you have smart pointers. You don't have to write shaders and setup Direct3D render states if you have Canvas class with methods like DrawSprite(x, y, color).

You can prepare a good library by yourself or download one of many freely available on the Internet and use just like in any other programming language. What you get in return when deciding to use C++ is great flexibility in defining how the interface of your library looks like. Thanks to templates, operator overloading and all that stuff you can create your own domain-specific language inside C++ (like the << operator is used to write to stream objects). At the same time, due to compiling to native code, creating objects on the stack and other language features you don't have to sacrifice performance. You don't have to use separate variables float x, y, z or dynamically allocate new Vector(x, y, z). You can define a vector structure with overloaded operators, use it conveniently and compiler will optimize the code so you can do thousands or millions of vector computations per second.

Comments (15) | Tags: c++ warsztat compo productions | Author: Adam Sawicki | Share

20:47
Sun
21
Oct 2012

C++ Lambdas - A Simple Explanation

Much can be said about theory behind lambda expressions, but lambdas in C++ - this new feature of C++11 supported by Visual C++ 2010, 2012, as well as other new compilers - can be explained very simply by following example. Today I wanted to write code that would sort a vector of pointers to entities in my 3D scene by distance from the camera, to ensure correct rendering of translucent objects.

std::vector<CEntity*> entitiesToRender;
vec3 cameraEyePos;
vec3 cameraForwardDir;

Vector in world space pointing forward from the camera - towards its positive Z axis - can be extracted from 3rd column of the view matrix. Dot product between this vector and a vector from camera position to object position gives length of the projection of one vector onto the other, which is the distance from the camera. But that's not the point here.

If you use STL, you know it's convenient to sort a vector using std::sort algorithm. Except if the contained type does not have operator< or you don't want it to be used (like here, as it would just compare pointers), you have to write a functor to compare elements. Lambda simplifies this task:

std::sort(
    entitiesToRender.begin(),
    entitiesToRender.end(),
    [=](CEntity* lhs, CEntity* rhs)
{
    return
        dot(lhs->GetPosition() - cameraEyePos, cameraForwardDir) >
        dot(rhs->GetPosition() - cameraEyePos, cameraForwardDir);
});

This code is equivalent to the traditional, more verbose version using functor:

class CompareFunctor
{
public:
    CompareFunctor(const vec3& cameraEyePos, const vec3& cameraForwardDir) :
        m_CameraEyePos(cameraEyePos),
        m_CameraForwardDir(cameraForwardDir)
    {
    }

    bool operator()(CEntity* lhs, CEntity* rhs) const
    {
        return
            dot(lhs->GetPosition() - m_CameraEyePos, m_CameraForwardDir) >
            dot(rhs->GetPosition() - m_CameraEyePos, m_CameraForwardDir);
    }

private:
    vec3 m_CameraEyePos;
    vec3 m_CameraForwardDir;
};

std::sort(
    entitiesToRender.begin(),
    entitiesToRender.end(),
    CompareFunctor(cameraEyePos, cameraForwardDir));

Parameters of lambda inside () are data passed to every call, like parameters of operator() in the functor. Inside [] we can specify what parameters are captured from the current context (local variables), which is equivalent to storing them as member variables inside the functor. [=] means capturing all necessary parameters by value, which are cameraEyePos and cameraForwardDir in this case. [&] would remember them by reference.

Comments (33) | Tags: c++ | Author: Adam Sawicki | Share

Pages: 1 2 3 ... 15 >

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2013 Adam Sawicki
Copyright © 2004-2013 Adam Sawicki