Switch off Memory Leak Detection in boost.Test - c++

I'm currently using boost.Test and I'm wondering if it might be possible to switch off the Memory Leak Detection, if one compiles in DEBUG Mode.
I don't want to use the command line parameter switch --detect_memory_leak=0. I'm looking for a kind of #define parameter, that switches off the memory leak detection feature in DEBUG mode.
It would be also suitable for me to switch off the memory detection feature by defining a certain compiler switch. I'm currently using Microsoft Visual Studio 2010.
#define BOOST_TEST_DETECT_MEMORY_LEAK 0 // Preprocesser switch I'm looking for!
#define BOOST_TEST_MODULE MyUnitTest
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(MySuite);
BOOST_AUTO_TEST_CASE(MyUnitTest) {
/// Following code has a memory leak
/// ....
}
BOOST_AUTO_TEST_SUITE_END()

Just found out that possibly the best way to turn off the detection of memory leaks is to include the following code snippet into one's tests.
#include <boost/test/debug.hpp>
struct GlobalFixture {
GlobalFixture() {
boost::debug::detect_memory_leaks(false);
}
~GlobalFixture() { }
};
BOOST_GLOBAL_FIXTURE(GlobalFixture);
Still, I was not able to switch off and to switch on the detection of memory leaks for single tests.

You can directly set the environment variable BOOST_TEST_DETECT_MEMORY_LEAK to 0 or use putenv :
#include <cstdlib>
//...
BOOST_AUTO_TEST_CASE(MyUnitTest) {
putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
//...
}
Edit
As you're using visual studio 2010, you can try _putenv or _wputenv :
#include <stdlib.h>
//...
BOOST_AUTO_TEST_CASE(MyUnitTest) {
_putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
//...
}
Otherwise, I found a function detect_memory_leaks in the Boost documentation but it seems to be only available on recent boost version.

_CrtSetDbgFlag(0);
is the only thing that mostly worked for me. Leak messages came out, but not enough to make me wait.
Here's some code detailing everything I tried:
struct GlobalFixture
{
GlobalFixture()
{
// This doesn't seem to do anything
// boost::debug::detect_memory_leaks(false);
// This either
//_putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
// This total hack also does nothing
// using namespace boost::unit_test::runtime_config;
// const_cast<boost::runtime::arguments_store&>(argument_store()).set(btrt_detect_mem_leaks, 0);
// This gets rid of most of the messages
_CrtSetDbgFlag(0);
}
};

Why not use the _DEBUG macro ?
#ifdef _DEBUG
#define BOOST_TEST_DETECT_MEMORY_LEAK 0
#endif

Related

which header file contains ThrowIfFailed() in DirectX 12

some part of code image, another part of code image, I am beginner to DirectX 12 (or Game Programming) and studying from Microsoft documentation. While using function ThrowIfFailed() I get an error from intellisense of vs2015 editor
This declaration has no storage class or type specifier.
Can anyone help.
As you are new to DirectX programming, I strongly recommend starting with DirectX 11 rather than DirectX 12. DirectX 12 assumes you are already an expert DirectX 11 developer, and is a quite unforgiving API. It's absolutely worth learning if you plan to be a graphics developer, but starting with DX 12 over DX 11 is a huge undertaking. See the DirectX Tool Kit tutorials for DX11 and/or DX12
For modern DirectX sample code and in the VS DirectX templates, Microsoft uses a standard helper function ThrowIfFailed. It's not part of the OS or system headers; it's just defined in the local project's Precompiled Header File (pch.h):
#include <exception>
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
// Set a breakpoint on this line to catch DirectX API errors
throw std::exception();
}
}
}
For COM programming, you must check at runtime all HRESULT values for failure. If it's safe to ignore the return value of a particular DirectX 11 or DirectX 12 API, it will return void instead. You generally use ThrowIfFailed for 'fast fail' scenarios (i.e. your program can't recover if the function fails).
Note the recommendation is to use C++ Exception Handling (a.k.a. /EHsc) which is the default compiler setting in the VS templates. On the x64 and ARM platforms, this is implemented very efficiently without any additional code overhead. Legacy x86 requires some additional epilog/prologue code that the compiler creates. Most of the "FUD" around exception handling in native code is based on the experience of using the older Asynchronous Structured Exception Handling (a.k.a. /EHa) which severely hampers the code optimizer.
See this wiki page for a bit more detail and usage information. You should also read the page on ComPtr.
In my version of the Direct3D Game VS Templates on GitHub, I use a slightly enhanced version of ThrowIfFailed which you could also use:
#include <exception>
namespace DX
{
// Helper class for COM exceptions
class com_exception : public std::exception
{
public:
com_exception(HRESULT hr) : result(hr) {}
virtual const char* what() const override
{
static char s_str[64] = {};
sprintf_s(s_str, "Failure with HRESULT of %08X",
static_cast<unsigned int>(result));
return s_str;
}
private:
HRESULT result;
};
// Helper utility converts D3D API failures into exceptions.
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
throw com_exception(hr);
}
}
}
This error is because some of your code are outside of any function.
Your error is just here :
void D3D12HelloTriangle::LoadPipeline() {
#if defined(_DEBUG) { //<= this brack is simply ignore because on a pre-processor line
ComPtr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) {
debugController->EnableDebugLayer();
}
} // So, this one closes method LoadPipeline
#endif
// From here, you are out of any function
ComPtr<IDXGIFactory4> factory;
ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
So to correct it :
void D3D12HelloTriangle::LoadPipeline() {
#if defined(_DEBUG)
{ //<= just put this bracket on it's own line
ComPtr<ID3D12Debug> debugController;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) {
debugController->EnableDebugLayer();
}
} // So, this one close method LoadPipeline
#endif
// From here, you are out of any function
ComPtr<IDXGIFactory4> factory;
ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));

Visual Studio sizeof() difference IntelliSense vs. compile-time

My code looks like this:
#include <stdio.h>
#pragma pack(1)
class MyClass
{
bool a;
bool b;
int c;
char d[3];
bool e[4];
};
#pragma pack()
int main()
{
printf("sizeof(MyClass)=%d\n", sizeof(MyClass));
return 0;
}
The output is:
sizeof(MyClass)=13
But when I "hover" over sizeof(MyClass) I get:
This wouldn't have been a big issue but I'm trying to implement a compile-time assertion and it isn't working (getting a red underline):
Anyone have any idea how to fix this?
This is not a difference between compile-time and run-time; it is a difference between your compiler and your IDE's "intellisense", the latter of which appears not to support/recognise the #pragma pack directive.
Ignore it. The size is 13.
Since you can actually build your program, you know that the compile-time assertion succeeds, despite the "red line".
It is probably worth adding a comment before that assertion, explaining that users of Visual Studio 2015 will see a false negative in their IDE for the following assertion.
You may also wish to raise a bug on Microsoft Connect, if there is not one already.

Warnings when compiling Boost libraries in C++ Builder

I am getting warnings when I am trying to include <boost/thread.hpp> in C++ Builder. For every unit I am including it, C++ Builder shows up these 2 lines:
thread_heap_alloc.hpp(59): W8128 Can't import a function being defined
thread_heap_alloc.hpp(69): W8128 Can't import a function being defined
Already tried some things, nothing worked though.
It compiles correctly, however, it's getting on my nerves. Why is this message being shown?
The lines are:
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
inline BOOST_THREAD_DECL void* allocate_raw_heap_memory(unsigned size)
{
void* const eap_memory=detail::win32::HeapAlloc(detail::win32::GetProcessHeap(),0,size);
if(!heap_memory)
{
throw std::bad_alloc();
}
return heap_memory;
}
inline BOOST_THREAD_DECL void free_raw_heap_memory(void* heap_memory)
{
BOOST_VERIFY(detail::win32::HeapFree(detail::win32::GetProcessHeap(),0,heap_memory)!=0);
}
where 59 is the { below the BOOST_THREAD_DECL, as is 69. Looks like BOOST_THREAD_DECL is not defined properly or mis-defined, trying to follow through the Boost code is not that easy.
This is Boost 1.39.
add #define BOOST_THREAD_USE_LIB before including the thread.hpp.
This is what I tested:
#define BOOST_THREAD_USE_LIB
extern "C"
{
namespace boost
{
void tss_cleanup_implemented( void )
{
/*
This function's sole purpose is to cause a link error in cases where
automatic tss cleanup is not implemented by Boost.Threads as a
reminder that user code is responsible for calling the necessary
functions at the appropriate times (and for implementing an a
tss_cleanup_implemented() function to eliminate the linker's
missing symbol error).
If Boost.Threads later implements automatic tss cleanup in cases
where it currently doesn't (which is the plan), the duplicate
symbol error will warn the user that their custom solution is no
longer needed and can be removed.*/
}
}
}
#include <boost/thread.hpp>
Then set 'Link with Dynamic RTL' and 'Link with Runtime Packages'.
This does a clean build and starts a thread properly.

how do I set a debug mode in c++

I would like to set a debug mode so that it prints the log statements only if the debug mode is on. For example if I have code like this
printf("something \n");
.
.
.
perror("something \n");
It only works if the debug flag is on.. I don't want to use "if" statements.
I think there is a clever way to do this using #define or something..
Thank is advance..
#ifdef _DEBUG // or #ifndef NDEBUG
#define LOG_MSG(...) printf(__VA_ARGS__) // Or simply LOG_MSG(msg) printf(msg)
#else
#define LOG_MSG(...) // Or LOG_MSG(msg)
#endif
On non-Debug built LOG_MSG would yeild to nothing. Instead of defining it with raw printf, you can have your custom logging-function, or class-method to be called.
Without going in to specific libraries or solutions, generally people make a logger class or function, and a single debug flag. The debug function checks this flag before calling printf or cout. Then in the rest of your code you simply call your debug function / method.
Here's an example:
class MyDebugger
{
private:
bool m_debug;
public:
MyDebugger();
void setDebug(bool debug);
void debug(const char* message);
};
MyDebugger::MyDebugger()
{
m_debug = false;
}
void MyDebugger::setDebug(bool debug)
{
m_debug = debug;
}
void MyDebugger::debug(const char* message)
{
if(m_debug)
{
cout << message << endl;
}
}
int main(int argc, char** argv)
{
MyDebugger debugger;
debugger.debug("This won't be shown");
debugger.setDebug(true);
debugger.debug("But this will");
return 0;
}
of course this is an incredibly naive implementation. In real logger classes there are many levels for finer-grained control of how much detail gets printed (levels like error, warning, info, and debug to differentiate the importance of the message). They might also let you log to files as well as stdout. Still this should give you a general idea.
In GCC, something like
#define debugprint(...) printf(__VA_ARGS__)
You can do a simple C-style macro definition (especially if you compiler is modern enough to do variable arguments macros, i.e. gcc or VS2005+) doing printf with a check of the debug level which can be a static global variable.
If you go with C++-style class similar to what #Chris suggests, I would make the logging function inline to ensure that when logging is disabled you are not wasting time on calling functions.

What Testframeworks are available for NI Lab Windows CVI?

I am forced to use NI Lab Windows CVI, and i would love work with TDD. However i could not find any testframeworks for that IDE. Are there any known solutions?
I just talked to someone at NI.
There are Unit Test Frameworks for NI Lab View wich is something completely different.
There is currently no solution from NI. In the past some people solved their issues using TestComplete - another route might be using CUnit.
EDIT:
Using CUNIT with CVI is really easy - though you still face some language Barriers:
#include "CUError.h"
#include "CUError.c"
#include "CUnit.h"
#include "MyMem.h"
#include "MyMem.c"
#include "TestDB.h"
#include "TestDB.c"
#include "TestRun.h"
#include "TestRun.c"
#include "Util.h"
#include "Util.c"
#include "Automated.h"
#include "Automated.c"
Using theese include statements should allow you to run this code:
static void testFail(void)
{
CU_ASSERT(0);
}
//Suite Definitions
static CU_TestInfo tests_GenList[] = {
{ "Should Fail", testFail },
CU_TEST_INFO_NULL,
};
static CU_SuiteInfo suites[] = {
{ "Generic List Suites", NULL, NULL, tests_GenList },
CU_SUITE_INFO_NULL,
};
void AddTests(void)
{
assert(NULL != CU_get_registry());
assert(!CU_is_test_running());
/* Register suites. */
if (CU_register_suites(suites) != CUE_SUCCESS) {
fprintf(stderr, "suite registration failed - %s\n",
CU_get_error_msg());
exit(EXIT_FAILURE);
}
}
int main (void)
{
CU_initialize_registry();
AddTests();
CU_set_output_filename("Result\\TestAutomated");
CU_list_tests_to_file();
CU_automated_run_tests();
CU_cleanup_registry();
return 0;
}
Also copy these files into your Result directory:
CUnit-List.dtd
CUnit-List.xsl
CUnit-Run.dtd
CUnit-Run.xsl
md2xml.pl
Memory-Dump.dtd
Memory-Dump.xsl
We also use CUnit with CMock (ThrowTheStick) over here. With cvi you can even automate the ruby scripts to execute the test_runner builder with somethine like
"%RUBY_HOME%\bin\ruby.exe" "%UNITY_HOME%\auto\generate_test_runner.rb"
Test_TestCycleFSM.c
in your pre-build steps. You maybe have to compile your project twice to generate the sourcefile and compile it then.
After all, CUnit seems to be the tests suite in C.