<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>manski's blog</title>
	
	<link>http://manski.net</link>
	<description />
	<lastBuildDate>Tue, 07 Feb 2012 14:21:42 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ManskisBlog" /><feedburner:info uri="manskisblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Meaningful C++ error message</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/aBxx1vGodxw/</link>
		<comments>http://manski.net/2012/02/07/meaningful-c-error-message/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 14:21:42 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ annoyances]]></category>

		<guid isPermaLink="false">http://manski.net/?p=2031</guid>
		<description><![CDATA[During my time as a student at the University of Stuttgart we had to learn the programming language Ada. Back then I was swearing about the compiler error message because they were totally meaningless (at least to me). I am currently working on a C++ project and I have to say that C++ isn&#8217;t an [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-02-07 14:34:42 -->During my time as a student at the University of Stuttgart we had to learn the programming language Ada. Back then I was swearing about the compiler error message because they were totally meaningless (at least to me).</p>
<p>I am currently working on a C++ project and I have to say that C++ isn&#8217;t an inch better than Ada. Consider the following code:</p>
<pre class="code">#include &lt;Windows.h&gt;

namespace Geometry {
  class Polyline { };
}

using Geometry::Polyline;

namespace OtherNS {
  Polyline* get() {
    return NULL;
  }
}</pre>
<p>Trying to compile this code gives you the following error message (on Visual C++ 2010):</p>
<pre class="code">using_test.cpp(10): error C2143: syntax error : missing ';' before '*'
using_test.cpp(10): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
using_test.cpp(10): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int</pre>
<p>What? Syntax error? And then you start looking where you missed a <code>;</code>.</p>
<p>The problem, however, is completely different. It&#8217;s because there is a <em>function</em> called <code>Polyline()</code> defined somewhere in <code>Windows.h</code> and now the compiler tries to use this function as return type instead of the class <code>Polyline</code> (but doesn&#8217;t say anything about that). &lt;irony&gt;This, of course, becomes totally clear just by reading this extremely meaningful error message.&lt;/irony&gt; *sigh*</p>
<p>GCC isn&#8217;t better here (in case you were blindly blaming Microsoft for writing bad error messages):</p>
<pre class="code">error: ‘Polyline’ does not name a type</pre>
<p>By the way, the problem can be solved by placing the <code>using</code> statement inside the <code>OtherNS</code> namespace.</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/aBxx1vGodxw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/02/07/meaningful-c-error-message/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/02/07/meaningful-c-error-message/</feedburner:origLink></item>
		<item>
		<title>C++ references and inheritance</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/t-yicJduQEE/</link>
		<comments>http://manski.net/2012/02/01/cpp-references-and-inheritance/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 09:23:20 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ annoyances]]></category>

		<guid isPermaLink="false">http://manski.net/?p=2004</guid>
		<description><![CDATA[The last few days I&#8217;ve been hunting a bug in a C++ project I&#8217;ve been working on. This hunt again showed me how easily you can break C++ programs by accident (something that isn&#8217;t possibly in Java or C#). You need to completely understand the inner workings of C++ to avoid such pitfalls. The whole [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-02-07 14:02:12 -->The last few days I&#8217;ve been hunting a bug in a C++ project I&#8217;ve been working on. This hunt again showed me how easily you can break C++ programs by accident (something that isn&#8217;t possibly in Java or C#). You need to completely understand the inner workings of C++ to avoid such pitfalls. </p>
<p>The whole problem was a result of me thinking that C++ references (<code>&amp;</code>) are just pointers (<code>*</code>) that have some restrictions (e.g. they can&#8217;t be <code>NULL</code>). Wrong! What&#8217;s even worse: They&#8217;re <em>sometimes</em> just pointers with some restriction. This makes them work in <em>some</em> cases but fail in others.</p>
<p>Let me take you on my journey and you&#8217;ll hopefully avoid this (very subtle) mistake in your work.</p>
<p><span id="more-2004"></span></p>
<h1 id="the_basic_idea">The Basic Idea</h1>
<p>Let&#8217;s examine the basic (and partially constructed) idea. Say, you have two classes, <code>BaseClass</code> and its child <code>ChildClass</code>:</p>
<pre class="code">class BaseClass { };
class ChildClass : public BaseClass { };</pre>
<p>Furthermore, say we have a pointer to an instance of <code>ChildClass</code> called <code>g_somePointer</code>.</p>
<pre class="code">// Exists as long as the program runs.
// NOTE: This is stored as a BaseClass pointer.
BaseClass* g_somePointer = new ChildClass();</pre>
<p>Now imagine, you want to write a wrapper class around another class providing you with a <em>reference</em> to this pointer <code>g_somePointer</code>. Let&#8217;s reduce the code to the function returning the reference (called <code>getReference()</code>) and the function wrapping it (called <code>getReferenceWrapper()</code>):</p>
<pre class="code">typedef BaseClass* BaseClassPointer;

const BaseClassPointer&amp; getReference() {
  // now &quot;ref&quot; is just another name for &quot;g_somePointer&quot;
  const BaseClassPointer&amp; ref = g_somePointer;
  return ref;
}

const BaseClassPointer&amp; getReferenceWrapper() {
  const BaseClassPointer&amp; ref = getReference();
  return ref;
}</pre>
<p>The last thing is some testing code which simply calls the wrapper function and does something with the returned pointer:</p>
<pre class="code">void main() {
  const BaseClassPointer&amp; ref = getReferenceWrapper();
  ref-&gt;doSomething();
}</pre>
<p>Executing this code will work as intended (but only tested with Visual C++ 2010 and g++ 4.6.1). <code>ref</code> in <code>main()</code> will &#8220;contain&#8221; the address to the <code>ChildClass</code> instance &#8211; the same as stored in <code>g_somePointer</code>.</p>
<h1 id="two_little_changes_turn_the_world_upside_down">Two Little Changes Turn the World Upside Down</h1>
<p>Now, for some reason you want to change the variable type of <code>g_somePointer</code> from <code>BaseClass*</code> to <code>ChildClass*</code>:</p>
<pre class="code">// Exists as long as the program runs.
ChildClass* g_somePointer = new ChildClass();</pre>
<p>The program will compile fine (even with the highest compiler warning level) and running the program will &#8211; at least with the compilers mentioned above &#8211; work as intended.</p>
<p>Let&#8217;s introduce a second &#8211; as it seems &#8211; totally unrelated change to the implementation of <code>getReferenceWrapper()</code>, adding a new local variable:</p>
<pre class="code">#include &lt;string&gt;

...

const BaseClassPointer&amp; getReferenceWrapper() {
  std::string someString = &quot;ignore me&quot;; // &lt;-- this is new

  const BaseClassPointer&amp; ref = getReference();
  return ref;
}</pre>
<p>This shouldn&#8217;t have any impact on the program, should it? </p>
<p>With me asking this question you probably already know the answer. Executing the program now should give you a segmentation fault/access violation.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/segmentation-fault.png" rel="shadowbox[sbpost-2004];player=img;" title="Segmentation fault when running the program"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=4d559c1036af32baa7a1fae93604985fdfd7ff0e_300x300_resize_if_larger" title="Segmentation fault when running the program" alt="Segmentation fault when running the program" width="300" height="140"/></a></div>
<p>What has happened? This second change seemed totally unrelated. Let&#8217;s debug the program. I&#8217;ll only show the relevant code and mark the current execution position with an arrow:</p>
<pre class="code">const BaseClassPointer&amp; getReferenceWrapper() {
  std::string someString = &quot;ignore me&quot;;

  const BaseClassPointer&amp; ref = getReference();
  return ref; // &lt;---
}</pre>
<p>At this line (<code>return ref;</code>) <code>ref</code> still contains the correct address.</p>
<pre class="code">const BaseClassPointer&amp; getReferenceWrapper() {
  std::string someString = &quot;ignore me&quot;;

  const BaseClassPointer&amp; ref = getReference();
  return ref;
} // &lt;---</pre>
<p>At this line, the content of <code>ref</code> suddenly has changed to some invalid garbage. &#8220;What&#8217;s going on here?&#8221; you might ask.</p>
<h1 id="the_cause">The Cause</h1>
<p>It may have looked like nothing but the actual cause for the problem was changing the data type of <code>g_somePointer</code> to <code>ChildClass*</code>. Let&#8217;s explore this.</p>
<p>First, the current implementation of <code>getReference()</code> is hiding the problem from the compiler. That&#8217;s why it can&#8217;t issue a warning (and neither Visual C++ nor g++ will).</p>
<pre class="code">const BaseClassPointer&amp; getReference() {
  const BaseClassPointer&amp; ref = g_somePointer;
  return ref;
}</pre>
<p>Let&#8217;s change this implementation to an equivalent (and more simple) one:</p>
<pre class="code">const BaseClassPointer&amp; getReference() {
  return g_somePointer;
}</pre>
<p>Now the compiler will give you a warning:</p>
<ul>
<li class="first-item">Visual C++: <em>warning C4172: returning address of local variable or temporary</em></li>
<li class="last-item">
<p>g++: <em>warning: returning reference to temporary [enabled by default]</em></p>
</li>
</ul>
<p><strong>Important:</strong> Don&#8217;t be as stupid as I was and try to &#8220;fix&#8221; the warning by using my initial implementation of <code>getReference()</code>. This warning is there for a reason and the reason is not that the compiler is too dumb to figure out what to do.</p>
<p>The compiler is telling you here that you&#8217;re returning a reference to a local variable. This is always a bad thing. The questions now are:</p>
<ul>
<li class="first-item">Why is this a bad thing?</li>
<li class="last-item">
<p>Where does the local variable or temporary (variable) come from?</p>
</li>
</ul>
<p><strong>Note:</strong> You won&#8217;t get this warning if you change the data type of <code>g_somePointer</code> back to <code>BaseClass*</code>. So, under some conditions the current implementation of <code>getReference()</code> is actually valid.</p>
<h2 id="why_is_this_a_bad_thing.3F_.28stack_frames.29">Why is this a bad thing? (Stack Frames)</h2>
<p>If you already know why returning a reference to a local variable is a bad thing (or if you just accept this fact), skip this section. If not, read on.</p>
<p>The problem here is that local variables reside on the so called &#8220;stack&#8221; (or &#8220;call stack&#8221;). This is a continuous section of memory that grows with each function that is called (and also shrinks again once the function returns). The following image shows the call stack for a function (= subroutine) named <code>DrawLine()</code>, called from a function named <code>DrawSquare()</code>:</p>
<div class="align-center image-align-center"><a href="http://en.wikipedia.org/wiki/File:Call_stack_layout.svg" rel="attachment" title="Example layout of a call stack showing stack frames and frame pointer (by R.S. Shaw)"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/callstack.png" title="Example layout of a call stack showing stack frames and frame pointer (by R.S. Shaw)" alt="Example layout of a call stack showing stack frames and frame pointer (by R.S. Shaw)"/></a></div>
<p>As you can see, there are two stack frames here (blue and green) &#8211; on for each function. Each stack frame contains the &#8220;Locals&#8221; (i.e. the local variables, such as &#8220;ref&#8221;) of the associated function. The stack frame (and with it the locals) of <code>DrawLine()</code> (the callee) is stored <em>above</em> the locals of <code>DrawSquare()</code> (the caller). Currently the function <code>DrawLine()</code> is being executed, indicated by the position of the &#8220;Stack Pointer&#8221;. When <code>DrawLine()</code> returns, the stack pointer will move to the top of <code>DrawSquare()</code>&#8216;s stack frame (the blue section). When this happens the stack frame of <code>DrawLine()</code> (the green section) will become <em>invalid</em>. Invalid here means that the memory section previously occupied by the stack frame (green section) must not be used anymore. If <code>DrawSquare()</code> now calls another function, this new function&#8217;s stack frame will replace the content in the green section with its own content.</p>
<p>Now, if you have a reference (or a pointer for that matter) to a <em>local</em> variable of <code>DrawLine()</code>, this reference will &#8220;point&#8221; to some content that&#8217;s no longer available. And that&#8217;s bad. The values of these references will change just by calling a function that doesn&#8217;t even know these references. On the other hand, if you don&#8217;t call another function, your code <em>may</em> work (just like our example code above did before introducing the local variable <code>someString</code>) and hide the problem. Small code changes or turning on code optimizations (like when switching from debug to release build) may (or may not) surface the problem again. This kind of problem is a real pain, as you can imagine.</p>
<h2 id="where_does_the_local_variable_or_temporary_.28variable.29_come_from.3F">Where does the local variable or temporary (variable) come from?</h2>
<p>Back to the warning. We&#8217;re being told by the compiler that we&#8217;re returning a temporary (i.e. a &#8220;variable&#8221; automatically created by the compiler). Where does this temporary come from?</p>
<p>Remember that the warning doesn&#8217;t appear when <code>g_somePointer</code> has the type <code>BaseClass*</code> (but it does appear if it has the data type <code>ChildClass*</code>). Here&#8217;s what the compiler basically converts the new implementation of <code>getReference()</code> into (I&#8217;ve actually extended the code a little bit to better show the problem):</p>
<pre class="code">BaseClass* g_somePointer;

const BaseClassPointer&amp; getReference() {
  // temporary is just another name for g_somePointer
  BaseClassPointer&amp; temporary = g_somePointer;
  return temporary;
}</pre>
<p>Now, when you change <code>g_somePointer</code>&#8216;s data type to <code>ChildClass*</code>, the compiler will convert the implementation into something slightly different:</p>
<pre class="code">ChildClass* g_somePointer;

const BaseClassPointer&amp; getReference() {
  // The &quot;static_cast&quot; isn't technically needed here.
  // It's just here to show that a cast is done here.
  BaseClass* localPointer = static_cast&lt;BaseClass*&gt;(g_somePointer);

  // temporary now is another name for localPointer (and no longer for g_somePointer)
  BaseClassPointer&amp; temporary = localPointer;
  return temporary;
}</pre>
<p>Here the compiler creates a local variable containing the pointer to the base class of <code>ChildClass</code>. This is required because in C++ the pointer to a base class doesn&#8217;t necessarily have to have the same address as the pointer to a child class. This is especially true when the child class inherits from multiple base classes. See this example:</p>
<pre class="code">class BaseClass1 { };
class BaseClass2 { };
class ChildClass : public BaseClass1, public BaseClass2 { };

ChildClass* ptr = new ChildClass();
BaseClass2* basePtr = ptr;
// now possibly: &quot;basePtr != ptr&quot;</pre>
<p>Because of this address change the compiler can&#8217;t just use <code>g_somePointer</code> for <code>temporary</code>. It needs to cast the instance first and then store it in some variable (here: <code>localPointer</code>). It than creates the reference to this local variable, which is bad as explained in the previous section.</p>
<p><strong>Side note:</strong> Adding the local variable <code>someString</code> to <code>getReferenceWrapper()</code> broke the code above because <code>std::string</code> is a class that has a destructor. The destructor is &#8220;just&#8221; a method (function) which is <em>automatically</em> called when the object (<code>someString</code>) goes out of scope. As I explained in the previous section, calling a function overwrites the call stack above the current function&#8217;s stack frame (i.e. the green part in the image above), thereby overwriting the memory section containing the address to the base class of <code>g_somePointer</code> (to which our reference pointed).</p>
<h1 id="working_example">Working Example</h1>
<p>I&#8217;ve attached the whole code of the example so that you can try it out for yourself.</p>
<p><a href="http://manski.net/wordpress/wp-content/uploads/2012/02/reference_problem.cpp_.txt" rel="attachment">reference_problem.cpp</a></p>
<h1 id="summary">Summary</h1>
<p>Returning a reference to a pointer will result in &#8220;unpredictable&#8221; (or at least undefined) behavior when the reference&#8217;s type is a base type of the pointer&#8217;s data type.</p>
<p>The following code will work (although you might consider it fragile)&#8230;</p>
<pre class="code">BaseClass* g_somePointer = ...
typedef BaseClass* BaseClassPointer;

const BaseClassPointer&amp; getRef() {
  return g_somePointer; // works
}</pre>
<p>&#8230; whereas the following code won&#8217;t (i.e. results in unpredictable behavior). Note that just the data type of <code>g_somePointer</code> changed to <code>ChildClass*</code>:</p>
<pre class="code">ChildClass* g_somePointer = ...  // &lt;-- different
typedef BaseClass* BaseClassPointer;

const BaseClassPointer&amp; getRef() {
  return g_somePointer; // illegal - introduces local variable
}</pre>
<p>This code is illegal because the compiler needs introduce a temporary, local variable in <code>getRef()</code> to store the resulting address of the (static) cast from <code>ChildClass*</code> to <code>BaseClass*</code>. And then the function returns a reference to this local variable instead of a reference to <code>g_somePointer</code>.</p>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/t-yicJduQEE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/02/01/cpp-references-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/02/01/cpp-references-and-inheritance/</feedburner:origLink></item>
		<item>
		<title>Verliebt in Siri</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/ma04DoU6e0I/</link>
		<comments>http://manski.net/2012/02/01/verliebt-in-siri/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 07:44:55 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Gagdets]]></category>
		<category><![CDATA[Videos]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[siri]]></category>

		<guid isPermaLink="false">http://manski.net/?p=2015</guid>
		<description><![CDATA[(via)]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-02-01 07:44:57 -->(<a href="http://http://apfelblog.ch/iphone/verliebt-in-siri-oder-so-sieht-siri-aus" target="_blank">via</a>)</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/ma04DoU6e0I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/02/01/verliebt-in-siri/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/02/01/verliebt-in-siri/</feedburner:origLink></item>
		<item>
		<title>Stoppt SOPA und PIPA!</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/E_2uYJQRaWw/</link>
		<comments>http://manski.net/2012/01/18/stop-sopa-and-pipa/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 09:10:42 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Private Blog]]></category>
		<category><![CDATA[Tech Blog]]></category>
		<category><![CDATA[pipa]]></category>
		<category><![CDATA[sopa]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1906</guid>
		<description><![CDATA[Mit diesem Bild werden Besucher der englischen Wikipedia am heutigen 18. Januar 2012 begrüßt. Grund: Protest gegen die US-Gesetzesentwürfe SOPA (Stop Online Piracy Act) und PIPA (ProtectIP Act). Einen guten (englisch-sprachigen) Artikel hat die Electronic Frontier Foundation dazu verfasst: How PIPA and SOPA Violate White House Principles Supporting Free Speech and Innovation. Irgendwie kommt mir [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/sopa-pipa-wikipedia.jpg" rel="shadowbox[sbpost-1906];player=img;" title="Wikipedia Seite wegen SOPA und PIPA heruntergefahren."><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=4c7dd72b1a8fdaf887fbc70efe1622f8a3c82741_500x500_resize_if_larger" title="Wikipedia Seite wegen SOPA und PIPA heruntergefahren." alt="Wikipedia Seite wegen SOPA und PIPA heruntergefahren." width="500" height="371"/></a></div>
<p>Mit diesem Bild werden Besucher der englischen Wikipedia am heutigen 18. Januar 2012 begrüßt. Grund: Protest gegen die US-Gesetzesentwürfe <strong>SOPA (Stop Online Piracy Act)</strong> und <strong>PIPA (ProtectIP Act)</strong>. Einen guten (englisch-sprachigen) Artikel hat die Electronic Frontier Foundation dazu verfasst: <a href="https://www.eff.org/deeplinks/2012/01/how-pipa-and-sopa-violate-white-house-principles-supporting-free-speech" target="_blank">How PIPA and SOPA Violate White House Principles Supporting Free Speech and Innovation</a>.</p>
<p>Irgendwie kommt mir das doch alles sehr <a href="http://de.wikipedia.org/wiki/Zugangserschwerungsgesetz" target="_blank">bekannt</a> vor.</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/E_2uYJQRaWw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/18/stop-sopa-and-pipa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/18/stop-sopa-and-pipa/</feedburner:origLink></item>
		<item>
		<title>IDisposable, Finalizer, and SuppressFinalize in C# and C++/CLI</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/gLYWewP2oC4/</link>
		<comments>http://manski.net/2012/01/16/idisposable-finalizer-and-suppressfinalize/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 08:39:29 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[c++/cli]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1886</guid>
		<description><![CDATA[The .NET framework features an interface called IDisposable. It basically exists to allow freeing unmanaged resources (think: C++ pointers). In most cases, you won&#8217;t need IDisposable when writing C# code. There are some exceptions though, and it becomes more important when writing C++/CLI code. The help page for IDisposable provides the code for IDisposable&#8216;s default [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->The .NET framework features an interface called <a href="http://msdn.microsoft.com/library/system.idisposable.aspx" target="_blank">IDisposable</a>. It basically exists to allow freeing unmanaged resources (think: C++ pointers). In most cases, you won&#8217;t need <code>IDisposable</code> when writing C# code. There are some exceptions though, and it becomes more important when writing C++/CLI code. </p>
<p>The <a href="http://msdn.microsoft.com/library/system.idisposable.aspx" target="_blank">help page</a> for <code>IDisposable</code> provides the code for <code>IDisposable</code>&#8216;s default implementation pattern in C#. This article will explain each part of it step by step and also provide the equivalent C++/CLI code in each step.</p>
<p><span id="more-1886"></span></p>
<h1 id="summary_-_for_the_impatient">Summary &#8211; for the impatient</h1>
<p>Here&#8217;s the summary of this article for those who don&#8217;t want to read the actual explanations.</p>
<p>Rules:</p>
<ul>
<li class="first-item">For a class owning <em>managed</em> resources, implement <code>IDisposable</code> (but not a finalizer).</li>
<li class="last-item">
<p>For a class owning at least one <em>unmanaged</em> resource, implement both <code>IDisposable</code> and a finalizer.</p>
</li>
</ul>
<p>C# code:</p>
<pre class="code">class DataContainer : IDisposable {
  public void Dispose() {
    Dipose(true);
    GC.SuppressFinalizer(this);
  }

  ~DataContainer() { // finalizer
    Dispose(false);
  }

  protected virtual void Dispose(bool disposing) {
    if (m_isDisposed)
      return;

    if (disposing) {
      // Dispose managed data
      //m_managedData.Dispose();
    }
    // Free unmanaged data
    //DataProvider.DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;
  }

  private bool m_disposed = false;
}</pre>
<p>C++/CLI code:</p>
<pre class="code">ref class DataContainer {
public:
  ~DataContainer() {
    if (m_isDisposed)
       return;

    // dispose managed data
    //delete m_managedData;
    this-&gt;!DataContainer(); // call finalizer
    m_isDisposed = true;
  }

  // Finalizer
  !DataContainer() {
    // free unmanaged data
    //DataProvider::DeleteUnmanagedData(m_unmanagedData);
  }

private:
  bool m_isDisposed; // must be set to false
};</pre>
<h1 id="the_root_of_all_evil">The Root of all Evil</h1>
<p>In C#, all classes are managed by the garbage collector. However, some things just can&#8217;t be expressed in pure managed code. In these cases you&#8217;ll need to store <em>unmanaged</em> data in a managed class. Examples are file handles, sockets, or objects created by unmanaged functions/frameworks.</p>
<p>So, here&#8217;s an example of a C# class containing unmanaged data:</p>
<pre class="code">class DataContainer {
  public DataContainer() {
    m_unmanagedData = DataProvider.CreateUnmanagedData();
  }

  private IntPtr m_unmanagedData;
}</pre>
<p>The equivalent C++/CLI example would look like this:</p>
<pre class="code">ref class DataContainer {
public:
  DataContainer() {
    m_unmanagedData = DataProvider::CreateUnmanagedData();
  }

private:
  IntPtr m_unmanagedData;
};</pre>
<p>The question now is: <strong>When gets the unmanaged data deleted?</strong></p>
<h1 id="finalizer">Finalizer</h1>
<p>Since our class <code>DataContainer</code> is a managed class, it is managed by .NET&#8217;s garbage collector. When the garbage collector determines that our instance of <code>DataContainer</code> is no longer needed, the object&#8217;s <em>finalizer</em> is called. So, that&#8217;s are good point to delete our unmanaged data.</p>
<p><em>Note:</em> Finalizers are also called <em>non-deterministic</em> destructors because the programmer has no influence over <em>when</em> the garbage collector will call the finalizer (once the object went out of scope). For <em>deterministic</em> destructors (explained in the next section), on the other hand, the programmer has full control when they are called.</p>
<p>In C# the finalizer method (internally named <code>Finalize()</code>) is created by using C++&#8217;s destructor notation (<code>~DataContainer</code>):</p>
<pre class="code">class DataContainer {
  public DataContainer() {
    m_unmanagedData = DataProvider.CreateUnmanagedData();
  }

  ~DataContainer() {
    DataProvider.DeleteUnmanagedData(m_unmanagedData);
  }

  private IntPtr m_unmanagedData;
}</pre>
<p>In C++/CLI the notation <code>~DataContainer()</code> is already reserved for deterministic destructors (because <em>all</em> destructors are deterministic in C++). So, here we must use the notation <code>!DataContainer</code> instead:</p>
<pre class="code">ref class DataContainer {
public:
  DataContainer() {
    m_unmanagedData = DataProvider::CreateUnmanagedData();
  }

  !DataContainer() {
    DataProvider.DeleteUnmanagedData(m_unmanagedData);
  }

private:
  IntPtr m_unmanagedData;
};</pre>
<p><em>Note:</em> Although you can declare a finalizer public in C++/CLI, it won&#8217;t be. So, don&#8217;t bother with its visibility. (In C# you get a compiler error when specifying anything but private visibility for the finalizer.)</p>
<h1 id="idisposable">IDisposable</h1>
<p>Since finalizers are non-deterministic, you have no control over when they will be called. When working with unmanaged data it may, however, be desirable to control the point of time when this unmanaged data will be deleted. The easiest way to do this: create a method for that. </p>
<p>The .NET framework provides a standard name for this method: <code>Dispose()</code>, defined by the <code>IDisposable</code> interface. This method is also called a &#8220;<em>deterministic</em> destructor&#8221; (whereas finalizers are non-deterministic destructors). Here&#8217;s the implementation in C#:</p>
<pre class="code">class DataContainer : IDisposable {
  public DataContainer() {
    m_unmanagedData = DataProvider.CreateUnmanagedData();
  }

  public void Dispose() {
    if (m_isDisposed)
       return;

    DataProvider.DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;
  }

  private bool m_sDisposed= false;
  private IntPtr m_unmanagedData;
}</pre>
<p>In C# you can either call the <code>Dispose()</code> method directly or use a <code>using</code> block. Note that we&#8217;ve added <code>m_isDisposed</code> to prevent the programmer from calling <code>Dispose()</code> multiple times.</p>
<p>In C++/CLI the <code>Dispose()</code> method is automatically created (and <code>IDisposable</code> is implemented) when creating a destructor (<code>~DataContainer</code>):</p>
<pre class="code">ref class DataContainer {
public:
  DataContainer() : m_isDisposed(false) {
    m_unmanagedData = DataProvider::CreateUnmanagedData();
  }

  ~DataContainer() {
    if (m_isDisposed)
       return;

    DataProvider::DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;
  }

private:
  bool m_isDisposed;
  IntPtr m_unmanagedData;
};</pre>
<p>In C++/CLI a deterministic destructor (or the <code>Dispose()</code> method) is called automatically when:</p>
<ul>
<li class="first-item">a class instance is on the stack (instead of the managed heap) and goes out of scope</li>
<li class="last-item">
<p>a class instance is on the managed heap and gets deleted via <code>delete myVar;</code></p>
</li>
</ul>
<p>This is identical with how you would &#8220;call&#8221; destructors in C++.</p>
<h1 id="combining_dispose_and_finalizer">Combining Dispose and Finalizer</h1>
<p>Since the programmer can forget to call <code>Dispose()</code>, it&#8217;s important to free unmanaged data in the finalizer (as well) to avoid memory leaks. So, often you want to combine <code>Dispose()</code> and the finalizer. Here&#8217;s how.</p>
<p>In C#, simply call <code>Dispose()</code> from the finalizer. Note that the finalizer will be called in any case, so the unmanaged data is freed even if the programmer forgets to call <code>Dispose()</code>.</p>
<pre class="code">class DataContainer : IDisposable {
  public DataContainer() {
    m_unmanagedData = DataProvider.CreateUnmanagedData();
  }

  public void Dispose() {
    if (m_isDisposed)
      return;

    DataProvider.DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;
  }

  // Finalizer
  ~DataContainer() {
    Dispose();
  }

  private bool m_disposed = false;
  private IntPtr m_unmanagedData;
}</pre>
<p>In C++/CLI we do the opposite: we call the finalizer (which isn&#8217;t possible in C#). This way is the cleaner. I&#8217;ll explain this a little later on.</p>
<pre class="code">ref class DataContainer {
public:
  DataContainer() : m_isDisposed(false) {
    m_unmanagedData = DataProvider::CreateUnmanagedData();
  }

  ~DataContainer() {
    if (m_isDisposed)
       return;

    this-&gt;!DataContainer();
    m_isDisposed = true;
  }

  // Finalizer
  !DataContainer() {
    DataProvider::DeleteUnmanagedData(m_unmanagedData);
  }

private:
  bool m_isDisposed;
  IntPtr m_unmanagedData;
};</pre>
<h1 id="managed_data">Managed Data</h1>
<p>Beside <em>unmanaged</em> data, a managed class can also contain <em>managed</em> data, i.e. instances of managed classes implementing <code>IDisposable</code>. Managed data is different from unmanaged data in that it should be disposed in <code>Dispose()</code> but <em>not</em> in the finalizer. This is because instances of managed classes may already have been garbage collected when the finalizer runs. </p>
<p>To avoid code duplication, <code>Dispose()</code> and the finalizer should be implemented like this (in pseudo-code):</p>
<pre class="code">void Dispose() {
  DisposeAllManagedData();
  Finalizer();
}

void Finalizer() {
  FreeAllUnmanagedData();
}</pre>
<p>This is why I called the C++/CLI way the &#8220;cleaner&#8221; way above. It implements the whole thing just like our pseudo-code:</p>
<pre class="code">ref class DataContainer {
public:
   ...

  ~DataContainer() {
    if (m_isDisposed)
       return;

    delete m_managedData; // dispose managed data
    this-&gt;!DataContainer(); // call finalizer
    m_isDisposed = true;
  }

  // Finalizer
  !DataContainer() {
    DataProvider::DeleteUnmanagedData(m_unmanagedData); // free unmanaged data
  }

private:
  bool m_isDisposed;
  IntPtr m_unmanagedData;
  IDisposable^ m_managedData;
};</pre>
<p>In C#, on the other hand, we can&#8217;t call the finalizer. So, we need to add a helper method called <code>Dispose(bool)</code>:</p>
<pre class="code">class DataContainer : IDisposable {
  ...

  public void Dispose() {
    Dipose(true);
  }

  ~DataContainer() {
    Dispose(false);
  }

  protected virtual void Dispose(bool disposing) {
    if (m_isDisposed)
      return;

    if (disposing) {
      m_managedData.Dispose();
    }
    DataProvider.DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;
  }

  private bool m_disposed = false;
  private IntPtr m_unmanagedData;
  private IDisposable m_managedData;
}</pre>
<p><em>Note:</em> The method <code>Dispose(bool)</code> is <code>virtual</code>. The idea behind this is that child classes can override this method to perform their own disposing. See below for more information. Note also that the C++/CLI compiler automatically creates this method when a class has a destructor. You can&#8217;t, however, use this method directly. It&#8217;s only visible from C# (or Visual Basic).</p>
<h1 id="suppressfinalize">SuppressFinalize</h1>
<p>The default dispose implementation pattern (as shown in <a href="http://msdn.microsoft.com/library/system.idisposable.aspx" target="_blank">IDisposable&#8217;s help page</a>) also adds the line <code>GC.SuppressFinalize(this);</code> to the <code>Dispose()</code> method. What does this method do and why do we need it?</p>
<p><code>GC.SuppressFinalize()</code> simply prevents the finalizer from being called. Since the finalizer&#8217;s only task is to free unmanaged data, it doesn&#8217;t need to be called if <code>Dispose()</code> was already called (and already freed all unmanaged data by calling the finalizer). Using <code>GC.SuppressFinalize()</code> give a small performance improvement but nothing more.</p>
<p>In C# the <code>Dispose()</code> method changes like this:</p>
<pre class="code">  public void Dispose() {
    Dipose(true);
    GC.SuppressFinalize(this);
  }</pre>
<p>In C++/CLI the destructor doesn&#8217;t change <em>at all</em>. That&#8217;s because the C++/CLI compiler automatically adds this code line to the destructor. (You can read about this and see a decompiled destructor <a href="http://www.codeproject.com/KB/mcpp/cppclidtors.aspx" target="_blank">here</a>. Search for &#8220;SuppressFinalize&#8221;.)</p>
<pre class="code">  ~DataContainer() {
    if (m_isDisposed)
       return;

    delete m_managedData; // dispose managed data
    this-&gt;!DataContainer(); // call finalizer
    m_isDisposed = true;
    // GC.SuppressFinalize(this) is automatically inserted here
  }</pre>
<h1 id="inheritance">Inheritance</h1>
<p>The default dispose implementation pattern used in the previous sections create a method called <code>Dispose(bool)</code>. This method is <code>protected virtual</code> and is meant to be overridden by child classes &#8211; in case they need to dispose some data of their own.</p>
<p>In C#, an implementation must </p>
<ol>
<li class="first-item">first check whether it already has been disposed,</li>
<li>then dispose everything,</li>
<li class="last-item">
<p>and then call the base method.</p>
</li>
</ol>
<p>The base method is called last to ensure that child classes are disposed before their parent classes. This is how destructors work in C++ and <code>Dispose()</code> mimics this behavior.</p>
<pre class="code">  protected virtual void Dispose(bool disposing) {
    if (m_isDisposed)
      return;

    if (disposing) {
      m_managedData.Dispose();
    }
    DataProvider.DeleteUnmanagedData(m_unmanagedData);
    m_isDisposed = true;

    // Dispose parent classes after child classes
    base.Dispose(disposing);
  }</pre>
<p><em>Note:</em> Each child class must manage its <em>own</em> <code>m_isDisposed</code> field.</p>
<p>In C++/CLI, again, the destructor remains the same. This is because it mimics the C++ destructor&#8217;s behavior which automatically calls its parent destructor.</p>
<pre class="code">  ~DataContainer() {
    if (m_isDisposed)
       return;

    delete m_managedData; // dispose managed data
    this-&gt;!DataContainer(); // call finalizer
    m_isDisposed = true;
    // GC.SuppressFinalize(this) is automatically inserted here
    // Base destructor is automatically called here
  }</pre>
<h1 id="when_to_use_idisposable.3A_3_easy_rules">When to Use IDisposable: 3 easy rules</h1>
<p>At this point I&#8217;d like to cite three easy rules when to use <code>IDisposable</code>. These rules were created by <a href="http://nitoprograms.blogspot.com/2009/08/how-to-implement-idisposable-and.html" target="_blank">Stephen Cleary</a> and I take no credit for them. I do, however, disagree with some statements (such as &#8220;No classes should be responsible for multiple unmanaged resources.&#8221;) and have adopted the rules in this case (see the link for the original description).</p>
<p><strong>Rule 1: Don&#8217;t do it (unless you need to).</strong></p>
<p>There are only two situations when <code>IDisposable</code> does need to be implemented:</p>
<ul>
<li class="first-item">The class owns unmanaged resources.</li>
<li class="last-item">
<p>The class owns managed (<code>IDisposable</code>) resources.</p>
</li>
</ul>
<p><b>Rule 2: For a class owning <em>managed</em> resources, implement IDisposable (but not a finalizer)</b></p>
<p>This implementation of <code>IDisposable</code> should only call <code>Dispose()</code> for each owned resource. It should not set anything to <code>null</code>.</p>
<p>The class should not have a finalizer.</p>
<p><strong>Rule 3: For a class owning at least one <em>unmanaged</em> resource, implement both IDisposable and a finalizer</strong></p>
<p>The finalizer should free the unmanaged resource, <code>Dispose</code> should dispose any managed resource and then call the finalizer.</p>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/gLYWewP2oC4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/16/idisposable-finalizer-and-suppressfinalize/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/16/idisposable-finalizer-and-suppressfinalize/</feedburner:origLink></item>
		<item>
		<title>Facebook and You</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/oHtTlyG-04w/</link>
		<comments>http://manski.net/2012/01/15/facebook-and-you/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 16:32:55 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Cartoon of the Day]]></category>
		<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Internet]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1890</guid>
		<description><![CDATA[Sehr böse BTW, ich mag Facebook. (via Geek &#038; Poke)]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->Sehr böse <img src='http://manski.net/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=bda680e721cd4be7b31baa88323058ef0f12d9a8_500x500_resize_if_larger" title="Facebook and You" alt="Facebook and You" width="500" height="398"/></div>
<p>BTW, ich mag Facebook.</p>
<p>(via <a href="http://geekandpoke.typepad.com/geekandpoke/2010/12/the-free-model.html" target="_blank">Geek &#038; Poke</a>)</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/oHtTlyG-04w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/15/facebook-and-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/15/facebook-and-you/</feedburner:origLink></item>
		<item>
		<title>Sharing project properties in Visual C++</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/ZpTt1gbB224/</link>
		<comments>http://manski.net/2012/01/11/sharing-project-properties-in-visual-c/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 17:24:28 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[property sheets]]></category>
		<category><![CDATA[visual c++]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[visual studio 2010]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1849</guid>
		<description><![CDATA[Everyone who has ever created and managed a C++ project in Visual Studio knows that there are hundreds of compiler switches and options to choose from. While setting the desired values for one project may be ok, it&#8217;s quite time-consuming and error-prone to do this for multiple projects. I&#8217;m currently working with a solution containing [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->Everyone who has ever created and managed a C++ project in Visual Studio knows that there are hundreds of compiler switches and options to choose from. While setting the desired values for one project may be ok, it&#8217;s quite time-consuming and error-prone to do this for multiple projects. I&#8217;m currently working with a solution containing about 30 or so projects that share most of their project settings. I always wished there was a way to sync or share these common settings among the projects in the solution. Fortunately, there is: <em>property sheets</em>. They&#8217;re a bit hidden though, so I&#8217;ll explain how to use them in this article.</p>
<p><em>Note:</em> This only applies to C++ and C++/CLI projects. .NET projects (C# and Visual Basic) don&#8217;t have that many options to be tweaked and (therefore?) can&#8217;t have shared settings.</p>
<p><em>Note 2:</em> This article describes property sheets as they appear in Visual Studio 2010. They may work slightly different in other versions of Visual Studio.</p>
<p><span id="more-1849"></span></p>
<h1 id="the_property_manager">The Property Manager</h1>
<p>While property sheets (file extension: <code>.props</code>) are simply XML files and therefore could be edited with a simple text editor, Visual Studio also provides an editor for property sheets. This editor is available through the so called Property Manager. To display the Property Manager pane, in the menu go to <code>View</code> &#8211;> <code>Other Windows</code> &#8211;> <code>Property Manager</code>.</p>
<p><em>Note:</em> Property sheet files share the same XML syntax as <code>.vcxproj</code> files.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/property-manager-in-menu.png" rel="shadowbox[sbpost-1849];player=img;" title="&quot;Property Manager&quot; in Visual Studio's menu"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=a69d7fb704a246dce4d4c8dace00d224355622eb_300x300_resize_if_larger" title="&quot;Property Manager&quot; in Visual Studio's menu" alt="&quot;Property Manager&quot; in Visual Studio's menu" width="300" height="309"/></a></div>
<p>This will open the Property Manager pane. For just one project (here called <code>MainConsoleProj</code>), the contents of the Property Manager will look like this:</p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/property-manager-new.png" title="Property Manager pane with just one project" alt="Property Manager pane with just one project"/></div>
<p>Let&#8217;s examine what you see here:</p>
<ol>
<li class="first-item">On the top (icon: <img src="http://manski.net/wordpress/wp-content/uploads/2012/01/project-icon.png" title="project-icon.png" alt="project-icon.png"/>) you see our project. If there were more projects in the solution, they&#8217;d listed here as well.</li>
<li>On the next level there are all configurations of the project on all supported platforms (icon: <img src="http://manski.net/wordpress/wp-content/uploads/2012/01/configuration-icon.png" title="configuration-icon.png" alt="configuration-icon.png"/>). There are usually the configurations &#8220;Debug&#8221; and &#8220;Release&#8221; on the platform &#8220;Win32&#8243;. These are the same configurations you have available in the project settings in the <code>Configuration</code> drop-down field. To keep things simply, from now on in this article a configuration-platform combination will be called just &#8220;configuration&#8221;.</li>
<li class="last-item">
<p>On the inner-most level you have the actual <em>property sheets</em>.</p>
</li>
</ol>
<p>Let&#8217;s examine the property sheets a bit closer:</p>
<ul>
<li class="first-item">There are two kinds of property sheets. I couldn&#8217;t find their official names, so let&#8217;s call them <em>Base Property Sheets</em> (icon: <img src="http://manski.net/wordpress/wp-content/uploads/2012/01/base-prop-icon.png" title="base-prop-icon.png" alt="base-prop-icon.png"/>) and <em>Custom Property Sheets</em> (icon: <img src="http://manski.net/wordpress/wp-content/uploads/2012/01/cust-prop-icon.png" title="cust-prop-icon.png" alt="cust-prop-icon.png"/>). You can edit only custom property sheets. Base property sheets are read-only.</li>
<li>Property sheets have an order in which they&#8217;re evaluated. This is important, if two property sheets define a value for the same setting. The order can be seen in the Property Manager and is bottom up. So in the image above, for the &#8220;Debug&#8221; configuration first <code>Core Windows Libraries</code> is evaluated, then <code>Unicode Support</code> and so forth. We&#8217;ll examine the effects of this order a little later.</li>
<li class="last-item">
<p>Property sheets belong to a certain configuration (such as &#8220;Debug|Win32&#8243;). The stack of property sheets defines the value that can be inherited for this specific configuration (i.e. that&#8217;s what you get when you choose <code>&lt;inherit from parent or project defaults&gt;</code> for a value in the project settings).</p>
</li>
</ul>
<p><em>Note:</em> The property sheet <code>Microsoft.Cpp.Win32.user</code> is located somewhere in the current user&#8217;s application settings. It&#8217;s contents therefore will be different for each user. By keeping it <em>the top item</em> in every configuration you allow the user to override any option, if necessary, without needing to change the project file.</p>
<h1 id="creating_a_shared_property_sheet">Creating a shared property sheet</h1>
<p>The first step is to create a new property sheet file. To do this, right-click on the project and choose <code>Add New Project Property Sheet</code>. This will add a new property sheet to all configurations of the project. In this article, we&#8217;ll called the file <code>commons.props</code> and place it in a directory called <code>shared-properties</code> directly in the solution directory.</p>
<p><em>Note:</em> You can also right-click on a configuration and choose the same menu item. In this case the new property sheet will only be added to the selected configuration. You can, of course, add this property sheet later to the other configurations as well.</p>
<p>As mentioned before, we want to keep the property sheet <code>Microsoft.Cpp.Win32.user</code> the top item in every configuration. So, select an instance of the new property sheets and click on the down arrow in the Property Manager&#8217;s toolbar. Repeat this also for the property sheet(s) in the other configuration(s).</p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/property-manager-move-down.png" title="Down button in Property Manager's toolbar" alt="Down button in Property Manager's toolbar"/></div>
<p>The result then should look like this:</p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/property-manager-result.png" title="Resulting layout in the Property Manager" alt="Resulting layout in the Property Manager"/></div>
<h1 id="editing_a_property_sheet">Editing a property sheet</h1>
<p>To edit a property sheet (file), simply double-click on it in the Property Manager.</p>
<p><em>Note:</em> The same property sheet file can be listed multiple times in the Property Manager. Editing one &#8220;instance&#8221; of this file will, of course, update all other &#8220;instances&#8221; as well (since all &#8220;instances&#8221; share the same file).</p>
<p>This will pop up a dialog that&#8217;s very similar to the &#8220;Project Settings&#8221; dialog of a C++ project. Note that since the property sheet file itself isn&#8217;t bound to any specified project kind or configuration, the dialog may display more options than are actually available to the project the property sheet is currently associated with.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/property-sheet-editor.png" rel="shadowbox[sbpost-1849];player=img;" title="The property sheet editor"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=340eca5e79e9b5c92b2ecfd3e7a5aab7116308ca_300x300_resize_if_larger" title="The property sheet editor" alt="The property sheet editor" width="300" height="215"/></a></div>
<p>Let&#8217;s demonstrate the effect of a property sheet with compiler switch <code>Warning Level</code>. But before we start editing the property sheet, we need to revert this switch&#8217;s its default value. To do this, open up the project settings for the current project (for example by select the project in the Property Manager and select <code>Properties</code> from the context menu). Then select <code>All Configurations</code> from the <code>Configuration</code> drop-down box and go to <code>C++</code> &#8211;> <code>General</code>. Then make sure that <code>Warning Level</code> is inheriting the default value (which should be <code>Level1 (/W1)</code>). If it&#8217;s not, its value will be printed in bold. In this case, click on the down arrow in the value field and select <code>&lt;inherit from parent or project defaults&gt;</code> (see screenshot).</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/inherit-warning-level.png" rel="shadowbox[sbpost-1849];player=img;" title="Set the Warning Level to its default value"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=acceb19d940f45b9f1db2680047d74d74be3f820_300x300_resize_if_larger" title="Set the Warning Level to its default value" alt="Set the Warning Level to its default value" width="300" height="152"/></a></div>
<p>After clicking on <code>Apply</code>, the result should look like this:</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/warning-level-default-value.png" rel="shadowbox[sbpost-1849];player=img;" title="Warning Level set to its default value"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=348cdb4bb0a9af6cff68fae0cfa5be48e2cc7f24_300x300_resize_if_larger" title="Warning Level set to its default value" alt="Warning Level set to its default value" width="300" height="97"/></a></div>
<p>Now, again, open the property sheet editor for the <code>common</code> property sheet we created earlier. There, set the <code>Warning Level</code> to <code>Level3 (/W3)</code>. Then click <code>OK</code>. </p>
<p><em>Note:</em> You may need to save the property sheet manually. For this, use the <code>Save</code> button in the Property Manager&#8217;s toolbar.</p>
<p>When you now open the project&#8217;s settings again, you should see that the inherited value (not in bold) of <code>Warning Level</code> <em>changed</em> from level 1 to level 3.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/default-value-w3.png" rel="shadowbox[sbpost-1849];player=img;" title="Changed inherited value"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=a4c3cd11eb3caacf395ca2becc32d45ddaa2b4e3_300x300_resize_if_larger" title="Changed inherited value" alt="Changed inherited value" width="300" height="120"/></a></div>
<p>That&#8217;s the effect of the property sheet. You can define as many settings in a single property sheet file as you want. Then you can add the same property sheet file to multiple project thereby sharing this set of common project settings among all projects.</p>
<p><em>Note:</em> A value of a setting specified in a property sheet is only used in a project, when there isn&#8217;t a custom value (printed in bold) assigned to this setting in the project settings. To take the value of the property sheet (instead of defining a value in the project file), select <code>&lt;inherit from parent or project defaults&gt;</code> from the drop-down menu of this setting.</p>
<h1 id="property_sheet_order">Property Sheet Order</h1>
<p>As mentioned earlier, the property sheets are applied in a certain order &#8211; from bottom to top as shown in Property Manager. When editing a property sheet, each setting already displays the inherited value &#8211; unless the property sheet defines its own value.</p>
<p>So, lets have a look at the property sheet <code>Microsoft.Cpp.Win32.user</code> (in one of the configurations). It still should be <em>the top item in the stack</em>. The value for <code>Warning Level</code> is already <code>Level3 (/W3)</code>. It&#8217;s inherited from one of the property sheets below &#8211; our &#8220;common&#8221; sheet in this case.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/user-sheet-above.png" rel="shadowbox[sbpost-1849];player=img;" title="User sheet above common sheet"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=22e9e6ed9960b38ea804209a689a8c82ed9a6473_300x300_resize_if_larger" title="User sheet above common sheet" alt="User sheet above common sheet" width="300" height="95"/></a></div>
<p>Now lets swap the <code>common</code> sheet with the <code>Microsoft.Cpp.Win32.user</code> sheet. This will move the <code>common</code> sheet to a position <em>above</em> of <code>Microsoft.Cpp.Win32.user</code>. Again, open the <code>Microsoft.Cpp.Win32.user</code> sheet. The <code>Warning Level</code> is now <code>Level1 (/W1)</code>, as it&#8217;s no longer inherited from the <code>common</code> sheet. In fact, the <code>common</code> sheet now inherits its values from the <code>Microsoft.Cpp.Win32.user</code> sheet.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/user-sheet-below.png" rel="shadowbox[sbpost-1849];player=img;" title="User sheet below common sheet"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=f0355cd37acf144cd32cf8c96265c75eb5bca26b_300x300_resize_if_larger" title="User sheet below common sheet" alt="User sheet below common sheet" width="300" height="94"/></a></div>
<h1 id="custom_variables_.28a.k.a._macros.29">Custom Variables (a.k.a. Macros)</h1>
<p>It&#8217;s possible to define your own custom variables (like the pre-defined <code>$(OutDir)</code> or <code>$(SolutionDir)</code>). These variables are called &#8220;Macros&#8221; in Visual Studio. To define one, open the property sheet editor and go to <code>User Macros</code>. There, you can add new macros with the <code>Add Macro</code> button. These macros then appear in the <code>Macros</code> section that is available when editing free text properties (such as paths).</p>
<h1 id="inheriting_from_other_property_sheets">Inheriting From Other Property Sheets</h1>
<p>Property sheets can inherit their values from other property sheets. You can either specify this inheritance &#8230;</p>
<ul>
<li class="first-item">in a <em>project file</em>: This is accomplished by adding the inherited property sheet to the Property Manager and move it below the inheriting property sheet.</li>
<li class="last-item">
<p>in a <em>property sheet file</em>: To do this, right-click on the inherit<em>ing</em> property sheet file in the Property Manager and choose <code>Add ... Property Sheet</code> and select/create the inherit<em>ed</em> property sheet. The inherit<em>ed</em> property sheet is now being displayed as child node of the inherit<em>ing</em> property sheet (see screenshot).</p>
</li>
</ul>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/inherited-property-sheet.png" title="The property sheet &quot;commons&quot; is inherited by &quot;commons-qt&quot;." alt="The property sheet &quot;commons&quot; is inherited by &quot;commons-qt&quot;."/></div>
<p>The XML code for inheritance is:</p>
<pre class="code">&lt;ImportGroup Label=&quot;PropertySheets&quot;&gt;
  &lt;Import Project=&quot;commons.props&quot; /&gt;
&lt;/ImportGroup&gt;</pre>
<h1 id="conditional_properties">Conditional Properties</h1>
<p>Property sheets can also contain <em>conditional property values</em>. This means that the value of a property depends on some other value. Usually, this is used to place values for debug and release builds in the same property sheet file. Unfortunately, you can edit these conditions in Visual Studio&#8217;s property editor. You need to use a text editor.</p>
<p><em>Note:</em> When you&#8217;ve modified a property sheet outside of Visual Studio, you need to close the solution(s) it belongs to and reopen them afterwards. Otherwise Visual Studio won&#8217;t detect the changes to the property sheet.</p>
<p>First, you can define conditions on single properties by using the <code>Condition</code> attribute:</p>
<pre class="code">&lt;Optimization Condition=&quot;'$(Configuration)|$(Platform)'=='Debug|Win32'&quot;&gt;Disabled&lt;/Optimization&gt;</pre>
<p>On the other hand, if you want to group several properties for a certain configuration, you can also add the <code>Condition</code> attribute to container elements (here: <code>&lt;ItemDefinitionGroup&gt;</code>):</p>
<pre class="code">&lt;ItemDefinitionGroup Condition=&quot;'$(Configuration)|$(Platform)'=='Release|Win32'&quot;&gt;
  &lt;ClCompile&gt;
    &lt;PreprocessorDefinitions&gt;QT_NO_DEBUG;QT_NO_DEBUG_OUTPUT;NDEBUG;%(PreprocessorDefinitions)&lt;/PreprocessorDefinitions&gt;
  &lt;/ClCompile&gt;
  &lt;Link&gt;
    &lt;GenerateDebugInformation&gt;false&lt;/GenerateDebugInformation&gt;
  &lt;/Link&gt;
&lt;/ItemDefinitionGroup&gt;</pre>
<p>You can find more information about conditions in the article <a href="http://msdn.microsoft.com/library/7szfhaft.aspx" target="_blank">&#8220;MSBuild Conditions&#8221; on MSDN</a>.</p>
<h1 id="property_sheet_xml_structure">Property Sheet XML Structure</h1>
<p>Property sheet files are XML files. The root element is called <code>&lt;Project&gt;</code> and in most cases you&#8217;ll work with the child elements <code>&lt;ItemDefinitionGroup&gt;</code> and <code>&lt;PropertyGroup&gt;</code>. It&#8217;s not always clear, in which kind of group to place a certain element. The easiest way to figure this out is to set the desired element in the project settings of a C++ project and then view the project file in a text editor. This is possible because property sheets and C++ project files (<code>.vcxproj</code>) use the same XML schema.</p>
<p>Additionally, you can have a look at the <a href="http://msdn.microsoft.com/library/5dy88c2e.aspx" target="_blank">XML tag descriptions on MSDN</a>, although there aren&#8217;t that descriptive.</p>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/ZpTt1gbB224" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/11/sharing-project-properties-in-visual-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/11/sharing-project-properties-in-visual-c/</feedburner:origLink></item>
		<item>
		<title>New iGlasses</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/zNYVaTHV_vw/</link>
		<comments>http://manski.net/2012/01/11/new-iglasses/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 16:55:10 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Real Life Pics]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1860</guid>
		<description />
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-31 19:56:27 -->
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2012/01/iglasses.jpg" title="My new iGlasses" alt="My new iGlasses"/></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/zNYVaTHV_vw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/11/new-iglasses/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/11/new-iglasses/</feedburner:origLink></item>
		<item>
		<title>Passing native pointers across C++/CLI assembly boundaries</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/OR5vz9N_uT0/</link>
		<comments>http://manski.net/2012/01/09/passing-native-pointers-across-ccli-assembly-boundaries/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:21:26 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Pinned]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[c++/cli]]></category>
		<category><![CDATA[native types]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1832</guid>
		<description><![CDATA[C++/CLI allows you to mix native C++ code with managed .NET code (which is extremly nice). Mixing such code also allows you to create methods in .NET class that take or return pointers to native (C++) classes. Unfortunately, this doesn&#8217;t work out of the box across assemblies (read: DLLs). If you define a .NET class [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 --><a href="http://manski.net/2011/04/19/cpp-cli-cheat-sheet/">C++/CLI</a> allows you to mix native C++ code with managed .NET code (which is extremly nice). Mixing such code also allows you to create methods in .NET class that take or return pointers to native (C++) classes. Unfortunately, this doesn&#8217;t work out of the box across assemblies (read: DLLs). If you define a .NET class in one assembly and this class has a method that returns a pointer, you may not be able to use this method from within <em>another</em> C++/CLI assembly. </p>
<p>This article describes the problem and shows solutions.</p>
<p><span id="more-1832"></span></p>
<h1 id="for_the_impatient">For the impatient</h1>
<p>For those of you that don&#8217;t want to read the whole article, here&#8217;s the summary:</p>
<ul>
<li class="first-item">
<p class="no-margin">Library providing method with native type:</p>
<ul>
<li class="first-item">Native types <em>outside</em> a C++/CLI project need to be made public in a C++/CLI project via <code> #pragma make_public(Type)</code></li>
<li>Native types <em>inside</em> a C++/CLI project need to be made public via keyword <code>public</code>.</li>
<li>This pragma has to be written in the <code>.h</code> file</li>
<li class="last-item">To prevent C3767, include the <code>.h</code> file before the pragma (i.e. don&#8217;t just use a forward declaration).</li>
</ul>
</li>
<li class="last-item">
<p class="no-margin">Library using the method:</p>
<ul>
<li class="first-item">Needs to include <code>.h</code> file of native type</li>
<li>Forward declaration <em>may</em> not be enough (gives linker warning)</li>
<li class="last-item">
<p>If the native type is defined <em>inside</em> a C++/CLI project, the project must be reference in the project settings via &#8220;Add Reference&#8221; <em>as well as</em> &#8220;Linker &#8211;> Input&#8221;.</p>
</li>
</ul>
</li>
</ul>
<h1 id="preparation">Preparation</h1>
<p>To illustrate the problem, we first create some projects that we can use as basis. Each project will only contain one or two classes, so nothing fancy here. I&#8217;ll assume you know how to create projects and how to enable and disable the <code>/clr</code> compiler switch to create C++/CLI and pure C++ project respectivly.</p>
<p>The first project (called &#8220;NativeLib&#8221;) is a pure C++ (no C++/CLI) and DLL project which provides a native (unmanaged) class called <code>MyNativeClass</code>. This class is the type that will later be passed across assembly boundaries. Here&#8217;s the source code (for the meaning of <code>NATIVE_LIB_EXPORT</code>, see <a href="http://manski.net/2011/11/09/creating-a-dll-project/#exporting_classes">Projects in Visual C++ 2010 &#8211; Part 1: Creating a DLL project</a>):</p>
<pre class="code">// MyNativeClass.h
#pragma once

#ifdef COMPILE_NATIVE_LIB
  #define NATIVE_LIB_EXPORT __declspec(dllexport)
#else
  #define NATIVE_LIB_EXPORT __declspec(dllimport)
#endif

class NATIVE_LIB_EXPORT MyNativeClass {
public:
  MyNativeClass(int val);

  int getValue() const;

private:
  int m_value;
};</pre>
<pre class="code">// MyNativeClass.cpp
#include &quot;MyNativeClass.h&quot;

MyNativeClass::MyNativeClass(int val) {
  this-&gt;m_value = val;
}

int MyNativeClass::getValue() const {
  return this-&gt;m_value;
}</pre>
<p>That&#8217;s it for the first project. The second project (named &#8220;ManagedProviderLib&#8221;; C++/CLI project) will provide the managed class <code>ManagedProvider</code> with a method the returns a pointer <code>MyNativeClass</code>. Here&#8217;s the source code:</p>
<pre class="code">// ManagedProvider.h
#pragma once

class MyNativeClass;

public ref class ManagedProvider {
public:
  ManagedProvider();

  MyNativeClass* getNativeClass();

private:
  MyNativeClass* m_nativeClass;
};</pre>
<pre class="code">// ManagedProvider.cpp
#include &quot;ManagedProvider.h&quot;
#include &lt;MyNativeClass.h&gt;

ManagedProvider::ManagedProvider() {
  this-&gt;m_nativeClass = new MyNativeClass(42);
}

MyNativeClass* ManagedProvider::getNativeClass() {
  return this-&gt;m_nativeClass;
}</pre>
<p>This should be pretty straight forward. Additionaly you need to add the project &#8220;NativeLib&#8221; to the include and library directories of &#8220;ManagedProviderLib&#8221;. </p>
<p>Here&#8217;s the final project structure:</p>
<pre class="code">NativeLib (pure C++)
  +- MyNativeClass.h
  +- MyNativeClass.cpp
ManagedProviderLib (C++/CLI)
  +- ManagedProvider.h
  +- ManagedProvider.cpp</pre>
<h1 id="the_problem">The Problem</h1>
<p>After we&#8217;ve created our skeletan projects, let&#8217;s explore the actual problem.</p>
<h2 id="what_does_work">What does work</h2>
<p>First, let&#8217;s create an example that does work. For this, we create a C++/CLI class called <code>InternalTestClass</code> and add it to the &#8220;ManagedProviderLib&#8221; project. This class will inherit <code>ManagedProvider</code> and have a method (<code>doSomething()</code>) that calls <code>ManagedProvider::getNativeClass()</code>. The project structure now is:</p>
<pre class="code">NativeLib (pure C++)
  +- MyNativeClass.h
  +- MyNativeClass.cpp
ManagedProviderLib (C++/CLI)
  +- ManagedProvider.h
  +- ManagedProvider.cpp
  +- InternalTestClass.h
  +- InternalTestClass.cpp</pre>
<p>And here&#8217;s the source code for <code>InternalTestClass</code>:</p>
<pre class="code">// InternalTestClass.h
#pragma once
#include &quot;ManagedProvider.h&quot;

public ref class InternalTestClass : ManagedProvider {
public:
  void doSomething();
};</pre>
<pre class="code">// InternalTestClass.cpp
#include &quot;InternalTestClass.h&quot;

void InternalTestClass::doSomething() {
  MyNativeClass* nativeClass = getNativeClass();
}</pre>
<p>##doSomething()## doesn&#8217;t do anything useful, but the point is that the project <em>compiles</em>. So, this shows that we <em>can</em> return the pointer to a native class here.</p>
<h2 id="what_doesn.27t_work_a.k.a_.22the_problem.22">What doesn&#8217;t work a.k.a &#8220;The Problem&#8221;</h2>
<p>Now, after having a working example, we&#8217;ll explore the actual problem. For this, we create a new C++/CLI project (called &#8220;ManagedExternalLib&#8221;) and add a managed class called <code>ExternalTestClass</code>. This will have the <em>same code</em> as <code>InternalTestClass</code>. The only difference is that <code>ExternalTestClass</code> is in a different project than its base class <code>ManagedProvider</code>. Here&#8217;s the project structure:</p>
<pre class="code">NativeLib (pure C++)
  +- MyNativeClass.h
  +- MyNativeClass.cpp
ManagedProviderLib (C++/CLI)
  +- ManagedProvider.h
  +- ManagedProvider.cpp
  +- InternalTestClass.h
  +- InternalTestClass.cpp
ManagedExternalLib (C++/CLI)
  +- ExternalTestClass.h
  +- ExternalTestClass.cpp</pre>
<p>And here&#8217;s the source code:</p>
<pre class="code">// ExternalTestClass.h
#pragma once

public ref class ExternalTestClass : ManagedProvider {
public:
  void doSomething();
};</pre>
<pre class="code">// ExternalTestClass.cpp
#include &quot;ExternalTestClass.h&quot;

class MyNativeClass;

void ExternalTestClass::doSomething() {
  // Compiler error C3767 - candidate function(s) not accessible
  MyNativeClass* nativeClass = getNativeClass();
}</pre>
<p>In a pure C++ class, this would compile &#8211; regardless of whether the &#8220;NativeLib&#8221; project is on the include and library path or not. We have a forward declaration of <code>MyNativeClass</code> and since we only work with the pointer of this class, we don&#8217;t need to know its size (which would be provided by including &#8220;MyNativeClass.h&#8221;). Also, since we don&#8217;t call any methods of <code>MyNativeClass</code> we don&#8217;t need the import lib of &#8220;NativeLib&#8221;.</p>
<p>But then this error doesn&#8217;t indicate a missing include file nor is it a linker error. Instead the error suggests that the method we want to call isn&#8217;t accessible (read: it&#8217;s <code>private</code> or <code>internal</code>). However, that&#8217;s not the case here.</p>
<h1 id="the_solution">The Solution</h1>
<p>The actual problem is not that the (C++/CLI) method is private but that <code>MyNativeClass</code> (pure C++) is private. That&#8217;s even mentioned (very briefly though) in <a href="http://msdn.microsoft.com/library/19dh8yat(v=VS.100).aspx" target="_blank">C3767&#8242;s description page</a>:</p>
<blockquote><p> C3767 may also be caused by a breaking change: native types are now private by default in a /clr compilation;
</p></blockquote>
<p>So, even if the native type was exported (via <code>__declspec(dllexport)</code>) in the native library, it can be made private by a managed library. (The reason behind this seems to be that the C++/CLI compiler generates thin (managed) wrappers around native types so that they can be called from managed code. See <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2008/02/16/net-to-c-bridge.aspx" target="_blank">here</a> for more information.)</p>
<h2 id="native_types_from_pure_c.2B.2B_projects">Native Types From Pure C++ Projects</h2>
<p>If the native type is defined in a pure C++ project (or in a framework for which you only have the header files), use <code> #pragma make_public(Type)</code>. You should place it in the <code>.h</code> after after including its header. So, our example code for <code>ManagedProvider.h</code> changes to this:</p>
<pre class="code">// ManagedProvider.h
#pragma once

#include &quot;MyNativeClass.h&quot;  // &lt;-- this is new (was &quot;class MyNativeClass;&quot; before)
#pragma make_public(MyNativeClass) // &lt;-- this is new

public ref class ManagedProvider {
  ...
};</pre>
<p><em>Notes:</em></p>
<ul>
<li class="first-item">Using <code>make_public</code> in a <code>.cpp</code> file instead of an <code>.h</code> file may result in the linker error <a href="http://msdn.microsoft.com/de-de/library/zkf0dz41.aspx" target="_blank">LNK2022</a> (metadata operation failed).</li>
<li class="last-item">
<p>The code above swapped the forward declaration (<code>class MyNativeClass.h</code>) with the <code> #include</code> statement. This is to be on the safe side. Forward declarations work in some cases, while they don&#8217;t work in others (resulting again in C3767 compiler errors).</p>
</li>
</ul>
<p>Compiling the whole solution now will give you a linker warning <a href="http://msdn.microsoft.com/de-de/library/h8027ys9.aspx" target="_blank">LNK4248</a> (unresolved typeref token). To fix this, you need to include the type&#8217;s <code>.h</code> file instead of just creating a forward reference. So, our &#8220;ExternalTestClass.cpp&#8221; changes to this:</p>
<pre class="code">// ExternalTestClass.cpp
#include &quot;ExternalTestClass.h&quot;

#include &lt;MyNativeClass.h&gt; // &lt;-- new; was &quot;class MyNativeClass;&quot; before

void ExternalTestClass::doSomething() {
  MyNativeClass* nativeClass = getNativeClass();
}</pre>
<p>Of course, this also allows you to actually do something (e.g. call methods) with the <code>nativeClass</code> pointer.</p>
<p><em>Note:</em> If you only want to store a pointer to a native class (i.e. don&#8217;t do anything with it), you don&#8217;t need to link against the native type&#8217;s <code>.lib</code> file.</p>
<h2 id="native_types_from_c.2B.2B.2Fcli_projects">Native Types From C++/CLI Projects</h2>
<p>The pragma <code>make_public</code> is used for native types defined in header file you can&#8217;t change. If, on the other hand, the native type is part of your C++/CLI project (&#8220;ManagedProviderLib&#8221; in this case), you can prefix the class definition with the keyword <code>public</code> (like you would for a managed type):</p>
<pre class="code">// MySecondNativeClass.h
#pragma once

#ifdef COMPILE_PRODUCER_LIB
  #define PRODUCER_LIB_EXPORT __declspec(dllexport)
#else
  #define PRODUCER_LIB_EXPORT __declspec(dllimport)
#endif

// Note that this is still a native type.
public class PRODUCER_LIB_EXPORT MySecondNativeClass {
  ...
};</pre>
<p>This keyword is only available in C++/CLI projects and has the same effect like <code>make_public</code>. <span class="strike">Unfortunately, I wasn&#8217;t able to get this example working, because I couldn&#8217;t figure out a way to <em>export</em> the methods of that type. I&#8217;ll update this section if I find some new information on that topic. (I&#8217;ve raised <a href="http://stackoverflow.com/questions/8786491/export-native-type-from-c-cli-project" target="_blank">this question at stackoverflow.com</a>.)</span></p>
<p>To use this type in another C++/CLI project, you need to reference the assembly&#8217;s <code>.lib</code> (here &#8220;ManagedProviderLib.lib&#8221;) <em>twice</em> in the project settings (here: of &#8220;ManagedExternalLib&#8221;):</p>
<ol>
<li class="first-item">Add a reference to the dependency project (here &#8220;ManagedProviderLib.lib&#8221;) in &#8220;Common Properties&#8221; &#8211;> &#8220;Framework and References&#8221; via &#8220;Add Reference&#8230;&#8221;.</li>
<li class="last-item">
<p>Also Add a reference to the dependency project in &#8220;Linker&#8221; &#8211;> &#8220;Input&#8221; &#8211;> &#8220;Additional Dependencies&#8221;.</p>
</li>
</ol>
<p>I&#8217;m not sure whether linking the same <code>.lib</code> file twice is a bug or working as intended, but surely it&#8217;s not very intuitive.</p>
<h1 id="source_code">Source Code</h1>
<p>I&#8217;ve created a small solution (for Visual Studios 2010) that contains the example source code described in this article.</p>
<p><a href="http://manski.net/wordpress/wp-content/uploads/2012/01/CLIAssemblyCrossBoundaryTest.zip" rel="attachment">CLIAssemblyCrossBoundaryTest.zip</a></p>
<h1 id="history">History</h1>
<ul>
<li class="first-item">2012-01-09 : Fixed using a native type from a C++/CLI project</li>
<li>2012-01-09 : No longer suggests forward declarations for public native types</li>
<li class="last-item">
<p>2012-01-09 : Published</p>
</li>
</ul>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/OR5vz9N_uT0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2012/01/09/passing-native-pointers-across-ccli-assembly-boundaries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2012/01/09/passing-native-pointers-across-ccli-assembly-boundaries/</feedburner:origLink></item>
		<item>
		<title>Eclipse and the JDK under Mac OS X Lion</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/SKf7JVL_pXI/</link>
		<comments>http://manski.net/2011/12/30/eclipse-and-the-jdk-under-mac-os-x-lion/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 12:50:24 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Pinned]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[jdk]]></category>
		<category><![CDATA[macosx]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1814</guid>
		<description><![CDATA[Java is open-source, fortunately. Accessing its source code is, unfortunately, not so intuitive on Mac OS X Lion when using Eclipse. This article will guide you through the steps required to be able to view Java&#8217;s source code in Eclipse. Determine your Java version Apple uses a different versioning system for Java than Oracle. For [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->Java is open-source, fortunately. Accessing its source code is, unfortunately, not so intuitive on Mac OS X Lion when using Eclipse. This article will guide you through the steps required to be able to view Java&#8217;s source code in Eclipse.</p>
<p><span id="more-1814"></span></p>
<h1 id="determine_java_version">Determine your Java version</h1>
<p>Apple uses a different versioning system for Java than Oracle. For example, on my system the actual Java version is &#8220;1.6.0_29&#8243; (determined by calling <code>java -version</code> from a terminal), but this version comes as &#8220;Java for Mac OS X 10.7 Update 1&#8243; through Apple&#8217;s Software Update.</p>
<p>To find out which Java Update you&#8217;re running, go to the <code>System Preferences</code> and click <code>Software Update</code>.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/software-update-in-system-preferences.png" rel="shadowbox[sbpost-1814];player=img;" title="Software Update in the Mac OS X System Preferences"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=00d6f0071dbd8c3f2a692f2ba2cd90fd78b7b204_300x300_resize_if_larger" title="Software Update in the Mac OS X System Preferences" alt="Software Update in the Mac OS X System Preferences" width="300" height="253"/></a></div>
<p>Then you click on <code>Installed Software</code> and search the list for the <em>latest</em> Java update (here &#8220;Update 1&#8243;).</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/find-latest-java-update.png" rel="shadowbox[sbpost-1814];player=img;" title="List of installed software updates"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=b5b7004836f8d0da73b145883f31d1a742866818_300x300_resize_if_larger" title="List of installed software updates" alt="List of installed software updates" width="300" height="205"/></a></div>
<p>That&#8217;s the &#8220;Java version&#8221; you need to know.</p>
<h1 id="downloading_the_jdk">Downloading the JDK</h1>
<p>When working with Java, you need to distinguish two Java software package types:</p>
<ul>
<li class="first-item">JRE: The &#8220;Java Runtime Environment&#8221; is necessary to <em>run</em> Java application. You cannot, however, <em>compile</em> Java programs with just the JRE.</li>
<li class="last-item">
<p>JDK: The &#8220;Java Development Kit&#8221; is required when you want to <em>compile</em> Java programs. The JDK includes the JRE, and also comes with Java&#8217;s source code.</p>
</li>
</ul>
<p><em>Remark:</em> Eclipse comes with its own Java compiler. That&#8217;s why you don&#8217;t need to install a JDK to create Java programs with Eclipse. Eclipse doesn&#8217;t ship with the Java source code though. That&#8217;s why we still need the JDK.</p>
<p>The JDK for Mac OS X comes as &#8220;Java Developer Package&#8221;. You can download it here:</p>
<p><a href="http://connect.apple.com/" target="_blank">http://connect.apple.com/</a></p>
<p>You&#8217;ll need an AppleID to download the JDK. Fortunately, it&#8217;s free but you still need to register it. (Tip: You can use the same you use in the iTunes Store.) After logging in, type &#8220;java developer package&#8221; in the search field (see screenshot).</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/download-jdk.png" rel="shadowbox[sbpost-1814];player=img;" title="Downloading the JDK from Apple's website"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=c499088882ea3ba6e58ea23a78cca8b8851b50aa_300x300_resize_if_larger" title="Downloading the JDK from Apple's website" alt="Downloading the JDK from Apple's website" width="300" height="189"/></a></div>
<p>Make sure the you download the Java Developer Package <em>matching your Java version</em>. In my case, this is &#8220;Mac OS X 10.7 Update 1&#8243;.</p>
<p><em>Note:</em> Don&#8217;t confuse &#8220;10.7&#8243; for Java 7. It&#8217;s still Java 6. (So don&#8217;t download a &#8220;10.6&#8243; version when you&#8217;re running Mac OS X Lion.)</p>
<p>Then install the JDK. This will install the JDK under:</p>
<pre class="code">/Library/Java/JavaVirtualMachines/</pre>
<p><em>Note:</em> There&#8217;s also the directory <code>/System/Library/Frameworks/JavaVM.framework/</code>. However, this directory seems to be deprecated.</p>
<p>The Java source code will be located here:</p>
<pre class="code">/Library/Java/JavaVirtualMachines/&lt;javaversion&gt;.jdk/Contents/Home/src.jar</pre>
<h2 id="check_an_already_installed_jdk">Check an already installed JDK</h2>
<p>To check whether you&#8217;ve already installed a JDK, check the list of installed updates (see <a href="#determine_java_version">above</a>) for an  entry called &#8220;Java Developer Package&#8221;.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/jre-and-jdk-in-software-updates.png" rel="shadowbox[sbpost-1814];player=img;" title="JRE and JDK in Software Updates"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=c9a164de7538b407ed224aaacbc2aa55a2b8eaa6_300x300_resize_if_larger" title="JRE and JDK in Software Updates" alt="JRE and JDK in Software Updates" width="300" height="203"/></a></div>
<p><em>Note:</em> Unfortunately, the Java Developer Package listed in the list doesn&#8217;t have any (visible) version information attached to it. I&#8217;m not sure whether the JDK will be updated automatically when a new version becomes available.</p>
<p>To check the actual Java version of the installed JDK, go to <code>/Library/Java/JavaVirtualMachines/</code> and check whether a package called like &#8220;1.6.0_29-b11-402.jdk&#8221; can be found there. In this example, the Java version would be &#8220;1.6.0_29&#8243;.</p>
<h1 id="using_the_jdk_in_eclipse">Using the JDK in Eclipse</h1>
<p>On Mac OS X, Eclipse provides an automatic way to determine the directory of the installed JDK. Go to the Eclipse Settings and open <code>Java</code> &#8211;> <code>Installed JREs</code>.</p>
<p>Then, by clicking on the <code>Search...</code> button, would find the newly installed JDK. Unfortunately, there seems to be a bug in Eclipse Ingido (3.7 &#8211; and probably in earlier versions, too) that prevents this button from working correctly. Clicking on it doesn&#8217;t do anything when there&#8217;s already one (and only one) JRE listed here; see screenshot.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/installed-jres1.png" rel="shadowbox[sbpost-1814];player=img;" title="Only one JRE is installed."><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=297c64fadbb10a2a760281fbe2d15491527cef15_300x300_resize_if_larger" title="Only one JRE is installed." alt="Only one JRE is installed." width="300" height="92"/></a></div>
<p>To fix this problem, do the following:</p>
<ol>
<li class="first-item"><em>Duplicate</em> the existing entry (by hitting the <code>Duplicate...</code> button)</li>
<li><em>Delete</em> the original entry; it&#8217;s the one with checked checkbox in front of it.</li>
<li>Then click <code>Search...</code>. This should add two new entries to the list (see next screenshot).</li>
<li><em>Delete</em> the entry you&#8217;ve created in step 1 (i.e. the duplicate of the original entry).</li>
<li><em>Check</em> one of the remaining entries. <strong>Note:</strong> The new two entries are linked. If you check one, both will be checked. Also, you can&#8217;t delete the entry for <code>/System/Library/Java/...</code>. Trying to do so will delete the other entry.</li>
<li>Close the Settings dialog with OK.</li>
<li class="last-item">
<p>Restart Eclipse. This will remove the wrong entry (the one for <code>/System/Library/Java/...</code>) from the list.</p>
</li>
</ol>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/installed-jres-after-search.png" rel="shadowbox[sbpost-1814];player=img;" title="The &quot;Installed JREs&quot; list after hitting &quot;Search...&quot;."><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=ab0ff614759ac01f46e61e8f71d1dbd319b9c429_300x300_resize_if_larger" title="The &quot;Installed JREs&quot; list after hitting &quot;Search...&quot;." alt="The &quot;Installed JREs&quot; list after hitting &quot;Search...&quot;." width="300" height="92"/></a></div>
<p>The list of installed JREs then should look like this:</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/installed-jres2.png" rel="shadowbox[sbpost-1814];player=img;" title="Final list contents for &quot;Installed JREs&quot;"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=f869313516d016a010ac934259e608ad8e83479b_300x300_resize_if_larger" title="Final list contents for &quot;Installed JREs&quot;" alt="Final list contents for &quot;Installed JREs&quot;" width="300" height="95"/></a></div>
<h2 id="manually_adding_a_jdk">Manually adding a JDK</h2>
<p>If you want (for any reason) to add the JDK manually, here&#8217;s how to do this:</p>
<ol>
<li class="first-item">Go to <code>Installed JREs</code> in the Eclipse Settings.</li>
<li>Click <code>Add...</code></li>
<li>Choose &#8220;MacOS X VM&#8221; and hit <code>Next...</code></li>
<li>Specify <code>/Library/Java/JavaVirtualMachines/&lt;javaversion&gt;.jdk/Contents/Home/</code> under <code>JRE Home</code>. <strong>Note:</strong> You need to type/paste the directory directly into the field. You can&#8217;t use the <code>Directory...</code> as the directories in the <code>JavaVirtualMachines</code> directory are so called &#8220;Mac OS X packages&#8221;. These directories are displayed as files and you can&#8217;t browse their contents from within the dialog.</li>
<li class="last-item">
<p>Give the JDK a meaningful name and hit <code>Finish</code>.</p>
</li>
</ol>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/manual-jdk-definition.png" rel="shadowbox[sbpost-1814];player=img;" title="Filled dialog for manual JDK definition"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=88026596b744ac5ad74bb80551f71c6d00a132d5_300x300_resize_if_larger" title="Filled dialog for manual JDK definition" alt="Filled dialog for manual JDK definition" width="300" height="233"/></a></div>
<h1 id="changelog">Changelog</h1>
<p>What changed?</p>
<ul>
<li>
<p><em>2011-12-30:</em> Published</p>
</li>
</ul>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/SKf7JVL_pXI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/30/eclipse-and-the-jdk-under-mac-os-x-lion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/30/eclipse-and-the-jdk-under-mac-os-x-lion/</feedburner:origLink></item>
		<item>
		<title>Assign DNS name to virtual machine (here: Parallels Desktop 7)</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/xckwvCnciuU/</link>
		<comments>http://manski.net/2011/12/28/assign-dns-name-to-virtual-machine-here-parallels-desktop-7/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 10:55:32 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[macosx]]></category>
		<category><![CDATA[networking]]></category>
		<category><![CDATA[virtualization]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1804</guid>
		<description><![CDATA[Assigning a DNS name to a virtual machine can be a convenient thing. Do this is not very complicated, it requires some technical skill though. This tutorial shows how to do this with a Ubuntu 11.10 Linux server running under Parallels Desktop 7 on Mac OS X Lion. The basic principals described in this article [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:06 -->Assigning a DNS name to a virtual machine can be a convenient thing. Do this is not very complicated, it requires some technical skill though. This tutorial shows how to do this with a Ubuntu 11.10 Linux server running under Parallels Desktop 7 on Mac OS X Lion. The basic principals described in this article work as well for any other combination, but that&#8217;s beyond this article (and that&#8217;s where your technical skill comes into play).</p>
<p><span id="more-1804"></span></p>
<h1 id="requirements">Requirements</h1>
<p>This article assumes that you&#8230;</p>
<ul>
<li class="first-item">&#8230; know your way around your operating system (Windows, Mac OS X, &#8230;)</li>
<li>&#8230; know what an IP address is and what&#8217;s it used for</li>
<li class="last-item">
<p>&#8230; have installed a hyper visor (e.g. VMWare, Parallels, or Virtual Box) and created a virtual machine with it.</p>
</li>
</ul>
<p>That&#8217;s basically it.</p>
<h1 id="the_goal">The Goal</h1>
<p>The goal is to be able to do something like this:</p>
<pre class="code">$ ping ubuntu-server
PING ubuntu-server (10.211.55.2): 56 data bytes
64 bytes from 10.211.55.2: icmp_seq=0 ttl=64 time=0.479 ms
64 bytes from 10.211.55.2: icmp_seq=1 ttl=64 time=0.348 ms
64 bytes from 10.211.55.2: icmp_seq=2 ttl=64 time=0.452 ms</pre>
<p>Here, we used the DNS name of our virtual server (called <code>ubuntu-server</code>) to do a ping. We didn&#8217;t need to know its IP address &#8211; which is the point of using DNS names. So, how does one assign such a name to a virtual server? That&#8217;s what this article is about.</p>
<h1 id="the_short_version">The Short Version</h1>
<p>If you really know your way around your OS, here&#8217;s the short version of what we&#8217;re going to do:</p>
<ol>
<li class="first-item">Assign a static IP address to the virtual machine (from within the virtual machine; see reasoning <a href="#static_ip_reasoning">below</a>)</li>
<li class="last-item">
<p>Add an entry to the OS&#8217; <code>hosts</code> file</p>
</li>
</ol>
<p>The remainder of this article describes the points above in more detail.</p>
<h1 id="static_ip_reasoning">Assign a static IP address</h1>
<p>To assign a static IP address (i.e. one that stays the same every time you start your virtual machine) one can think of two ways of doing this:</p>
<ol>
<li class="first-item">Let the virtual machine (i.e. the simulat<em>ed</em> computer) decide what IP address to use.</li>
<li class="last-item">
<p>Let the hyper visor (i.e. the simulat<em>ing</em> program) decide what IP address to use.</p>
</li>
</ol>
<p>In my opinion that latter would be the cleaner way. Simply tell your hyper visor software what IP address to assign to the virtual machine. Unfortunately that&#8217;s no that simple. A virtual machine could itself simulate multiple network adapters where each one would acquire an IP address. Which of these adapters then would the hyper visor assign the static IP address to? That&#8217;s probably why none of the hyper visors I used provided an option for this (at least none that&#8217;s easily reachable).</p>
<p>So, the way to go is to let the virtual machine (i.e. the simulated computer) decide which IP address to use.</p>
<h2 id="free_some_ip_addresses_.28from_the_dhcp_server.29">Free some IP addresses (from the DHCP server)</h2>
<p>To use an IP address we first need to make sure that there are IP addresses free to be used. By default, at least in Parallels Desktop, the DHCP server take up all available IP addresses in the specified IP range. So let&#8217;s change that. (This probably requires all virtual machines to be shut down.)</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/parallels-settings.png" rel="shadowbox[sbpost-1804];player=img;" title="Parallels Network Settings 1"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=b0e786e804fb3ee30159c7c58307743977d63d27_300x300_resize_if_larger" title="Parallels Network Settings 1" alt="Parallels Network Settings 1" width="300" height="103"/></a></div>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/parallels-network-settings.png" rel="shadowbox[sbpost-1804];player=img;" title="Parallels Desktop Network Settings 2"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=f60953f679f7a0d337332c63fc4ea5a349f09220_300x300_resize_if_larger" title="Parallels Desktop Network Settings 2" alt="Parallels Desktop Network Settings 2" width="300" height="361"/></a></div>
<p>In Parallels Desktop, go to the program&#8217;s settings (not the settings of the virtual machine), then to <code>Advanced</code> and click on <code>Change Settings...</code> (as shown in the first screenshot). This will open the network settings. There you select the network type you used for your virtual machine (either <code>Shared</code> or <code>Host-Only</code>) and change the last number group of the IPv4 DHCP start address. I&#8217;ve set it to 20 in the screenshot above. This will free the first 20 IP addresses (1 &#8211; 19) so that they can be used as static IP addresses.</p>
<h2 id="assign_the_static_ip_address_in_the_virtual_machine">Assign the static IP address in the virtual machine</h2>
<p>Next, start the virtual machine you want to assign a name to. Here you need to assign it one of the IP addresses we&#8217;ve just freed. This procedure highly depends on the operating system your virtual machine is running. So, I&#8217;ve compile a small list of how to do this on some of the popular operating systems:</p>
<ul>
<li class="first-item"><a href="http://www.onlinehowto.net/how-to-change-my-ip-address-in-windows-xp/810" target="_blank">Windows XP</a></li>
<li><a href="http://windows.microsoft.com/en-US/windows7/Change-TCP-IP-settings" target="_blank">Windows 7</a></li>
<li><a href="http://www.addictivetips.com/ubuntu-linux-tips/how-to-assign-static-ip-address-in-ubuntu-linux/" target="_blank">Ubuntu with graphical desktop</a></li>
<li class="last-item">
<p><a href="http://www.howtogeek.com/howto/ubuntu/change-ubuntu-server-from-dhcp-to-a-static-ip-address/" target="_blank">Ubuntu/Debian with console only</a></p>
</li>
</ul>
<p>What to enter:</p>
<ul>
<li class="first-item"><strong>IP address:</strong> The IP address you want to assign to the virtual machine. It doesn&#8217;t really matter which one you choose as long as it&#8217;s not used for any other virtual machine. (You may start with number <code>1</code> for the last number block.) In my case, I&#8217;ve assigned the address &#8220;10.211.55.2&#8243; to the virtual machine.</li>
<li><strong>Subnet Mask:</strong> Should be &#8220;255.255.255.0&#8243;, unless you know what you&#8217;re doing.</li>
<li><strong>Gateway:</strong> The IP address of the virtual router of your hyper visor. In Parallels Desktop this is the first IP address of the IP range specified in the options. In my case, this is &#8220;10.211.55.20&#8243; (see the screenshot above).</li>
<li class="last-item">
<p><strong>DNS Server:</strong> This is usally the same address as the gateway.</p>
</li>
</ul>
<h1 id="add_ip_address_to_hosts">Add IP address to hosts</h1>
<p>The last step is to add the newly assign static IP address to the <code>hosts</code> file of the host OS (i.e. not the guest OS). Fortunately, this file has the same format on most operating systems (including Windows, Mac OS, and Linux). Only the directory where to find it is different:</p>
<ul>
<li class="first-item">Windows: <code>%SystemRoot%\system32\drivers\etc\hosts</code></li>
<li>Linux/Mac OS X: <code>/etc/hosts</code></li>
<li class="last-item">
<p><a href="http://en.wikipedia.org/wiki/Hosts_(file)" target="_blank">Other operating systems and more details</a></p>
</li>
</ul>
<p>The format of the <code>hosts</code> is quite simple. Each line contains of a IP address and the DNS name(s) that are assigned to it. For example:</p>
<pre class="code">10.211.55.2  ubuntu-server</pre>
<p>On Mac OS X I recommend using <a href="http://www.barebones.com/products/textwrangler/" target="_blank">TextWrangler</a>. It&#8217;s a free text editor for Mac OS X that allows you to edit hidden and locked files (both applies to the <code>hosts</code> file). I&#8217;ve created an article for this topic <a href="http://manski.net/2011/12/28/editing-hidden-and-locked-files-on-mac-os-x-with-textwrangler/">here</a>.</p>
<p>After you&#8217;ve changed the <code>hosts</code> file, you may need to run the following command (from the &#8220;Terminal&#8221;):</p>
<pre class="code">$ dscacheutil -flushcache</pre>
<p>Now you should be able to ping your virtual machine by using its name rather than its IP address.</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/xckwvCnciuU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/28/assign-dns-name-to-virtual-machine-here-parallels-desktop-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/28/assign-dns-name-to-virtual-machine-here-parallels-desktop-7/</feedburner:origLink></item>
		<item>
		<title>Editing hidden and locked files on Mac OS X with TextWrangler</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/AL5Mp95BMLY/</link>
		<comments>http://manski.net/2011/12/28/editing-hidden-and-locked-files-on-mac-os-x-with-textwrangler/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 10:46:46 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[macosx]]></category>
		<category><![CDATA[system files]]></category>
		<category><![CDATA[textwrangler]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1807</guid>
		<description><![CDATA[Sometimes one needs to edit a system configuration file on Mac OS X. While these files are usually text files, you can&#8217;t used Mac OS&#8217; &#8220;TextEdit&#8221; tool to do this. Fortunately, there is a free alternative to &#8220;TextEdit&#8221; called TextWrangler. Important: Make sure that you don&#8217;t use the AppStore version as this version doesn&#8217;t allow [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->Sometimes one needs to edit a system configuration file on Mac OS X. While these files are usually text files, you can&#8217;t used Mac OS&#8217; &#8220;TextEdit&#8221; tool to do this. Fortunately, there is a free alternative to &#8220;TextEdit&#8221; called <a href="http://www.barebones.com/products/textwrangler/" target="_blank">TextWrangler</a>.</p>
<p><strong>Important:</strong> Make sure that you <em>don&#8217;t use the AppStore version</em> as this version doesn&#8217;t allow editing locked files. (Apple&#8217;s store guidelines prohibit this.)</p>
<p>First, select <code>File</code> &#8211;> <code>Open...</code> from the menu. Then, since system configuration files are often hidden or in hidden folders, select <code>Show hidden items</code> at the bottom of the &#8220;Open&#8221; dialog.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/12/textwrangler-open-dialog.png" rel="shadowbox[sbpost-1807];player=img;" title="Open Dialog in TextWrangler"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=298da8b068ba252376dce809c04bef2fc58bd23d_500x500_resize_if_larger" title="Open Dialog in TextWrangler" alt="Open Dialog in TextWrangler" width="500" height="553"/></a></div>
<p>Then open the file you want to edit. You may notice that the file is in read-only mode (represented by the icon in the upper left corner).</p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2011/12/textwrangler-readonly.png" title="TextWrangler in read-only mode" alt="TextWrangler in read-only mode"/></div>
<p>To switch to write mode, either click this icon or start editing the file&#8217;s content. In both cases you&#8217;ll be asked to unlock the file. After that, you can edit the file.</p>
<p>When you&#8217;re done, simply save the file. You&#8217;ll be asked for your password since you&#8217;re editing a system file (that doesn&#8217;t belong to you). And that&#8217;s it.</p>
<p><em>Note:</em> The AppStore version doesn&#8217;t ask you for your password but instead asks you to save the file under a different name.</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/AL5Mp95BMLY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/28/editing-hidden-and-locked-files-on-mac-os-x-with-textwrangler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/28/editing-hidden-and-locked-files-on-mac-os-x-with-textwrangler/</feedburner:origLink></item>
		<item>
		<title>Frohe Weihnachten</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/f8WaAcjQcGA/</link>
		<comments>http://manski.net/2011/12/24/frohe-weihnachten-2/#comments</comments>
		<pubDate>Sat, 24 Dec 2011 19:00:26 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Private Blog]]></category>
		<category><![CDATA[Tech Blog]]></category>
		<category><![CDATA[christmas]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1789</guid>
		<description><![CDATA[Frohe Weihnachten, liebe Leser.]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->Frohe Weihnachten, liebe Leser. <img src='http://manski.net/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="align-center image-align-center"><a href="http://fav.me/d1724k5" rel="attachment" title="A small Gift for Christmas - by Vladstudio"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=beaa5704c27bc414c75cdcb93c8746bebd1f7ac2_500x500_resize_if_larger" title="A small Gift for Christmas - by Vladstudio" alt="A small Gift for Christmas - by Vladstudio" width="500" height="375"/></a></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/f8WaAcjQcGA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/24/frohe-weihnachten-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/24/frohe-weihnachten-2/</feedburner:origLink></item>
		<item>
		<title>Red Bull</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/HL22wwZq5I4/</link>
		<comments>http://manski.net/2011/12/23/red-bull/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 14:08:01 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Cartoon of the Day]]></category>
		<category><![CDATA[Funny Stuff]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1801</guid>
		<description />
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-31 19:56:27 -->
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2011/12/redbull.jpg" title="redbull.jpg" alt="redbull.jpg"/></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/HL22wwZq5I4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/23/red-bull/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/23/red-bull/</feedburner:origLink></item>
		<item>
		<title>Users vs. Programmers</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/hReEjlm9br4/</link>
		<comments>http://manski.net/2011/12/22/users-vs-programmers/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 14:03:18 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Funny Stuff]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1798</guid>
		<description><![CDATA[So true &#8211; oh, did I say that out loud?]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->So true &#8211; oh, did I say that out loud? <img src='http://manski.net/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2011/12/ProgrammersvsUsers.jpg" title="Programmers vs. Users" alt="Programmers vs. Users"/></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/hReEjlm9br4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/22/users-vs-programmers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/22/users-vs-programmers/</feedburner:origLink></item>
		<item>
		<title>Cello Wars</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/oAfWvRYH1zc/</link>
		<comments>http://manski.net/2011/12/07/cello-wars/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 13:05:49 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Musik and Audio]]></category>
		<category><![CDATA[Private Blog]]></category>
		<category><![CDATA[Videos]]></category>
		<category><![CDATA[cello]]></category>
		<category><![CDATA[parodie]]></category>
		<category><![CDATA[star wars]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1787</guid>
		<description><![CDATA[Einfach nur cool]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-31 19:56:27 -->Einfach nur cool <img src='http://manski.net/wordpress/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/oAfWvRYH1zc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/07/cello-wars/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/07/cello-wars/</feedburner:origLink></item>
		<item>
		<title>Musik von Old School Elektronik</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/HhDIezwNDcY/</link>
		<comments>http://manski.net/2011/12/06/musik-von-old-school-elektronik/#comments</comments>
		<pubDate>Tue, 06 Dec 2011 07:22:52 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Musik and Audio]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1785</guid>
		<description><![CDATA[Click here to view the embedded video.]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 --><p><a href="http://manski.net/2011/12/06/musik-von-old-school-elektronik/"><em>Click here to view the embedded video.</em></a></p></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/HhDIezwNDcY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/12/06/musik-von-old-school-elektronik/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/12/06/musik-von-old-school-elektronik/</feedburner:origLink></item>
		<item>
		<title>Reichhaltiges Gebäck-Angebot</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/U9y1Arxlae8/</link>
		<comments>http://manski.net/2011/11/22/reichhaltiges-geback-angebot/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 13:25:37 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Real Life Pics]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1778</guid>
		<description />
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-31 19:56:27 -->
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/reichhaltiges-gebaeck-angebot.jpg" rel="shadowbox[sbpost-1778];player=img;" title="Reichhaltiges Gebäck-Angebot"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=0a65aa70e382b36713f94962b0a0907eb97d0cb3_500x500_resize_if_larger" title="Reichhaltiges Gebäck-Angebot" alt="Reichhaltiges Gebäck-Angebot" width="500" height="296"/></a></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/U9y1Arxlae8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/22/reichhaltiges-geback-angebot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/22/reichhaltiges-geback-angebot/</feedburner:origLink></item>
		<item>
		<title>I believe I can fly</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/UPW7fa3X14I/</link>
		<comments>http://manski.net/2011/11/14/i-believe-i-can-fly/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 19:06:39 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Private Blog]]></category>
		<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1772</guid>
		<description><![CDATA[Einfach nur krass&#8230;]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-31 19:56:27 -->Einfach nur krass&#8230;</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/UPW7fa3X14I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/14/i-believe-i-can-fly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/14/i-believe-i-can-fly/</feedburner:origLink></item>
		<item>
		<title>Android Source Code in Eclipse</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/7v_eISdPmZ8/</link>
		<comments>http://manski.net/2011/11/14/android-source-code-in-eclipse/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 16:36:04 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[eclipse]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1767</guid>
		<description><![CDATA[Google made developing an Android app fairly simple. Everything you need can be downloaded for free from Android&#8217;s development site. This includes the Android API, an Android emulator (for running Android apps directly on your computer), and an Eclipse plugin called ADT (Android Developer Tools). However, there&#8217;s one thing missing: the Java source code. The [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->Google made developing an Android app fairly simple. Everything you need can be downloaded for free from <a href="http://developer.android.com/sdk/installing.html" target="_blank">Android&#8217;s development site</a>. This includes the Android API, an Android emulator (for running Android apps directly on your computer), and an Eclipse plugin called ADT (Android Developer Tools). However, there&#8217;s one thing missing: the <em>Java source code</em>.</p>
<h2 id="the_problem">The Problem</h2>
<p>Despite the fact the Android is (supposed to be) an open source project, the downloads don&#8217;t include the source code of Android. So, when opening an Android class in Eclipse, you may see something like this:</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/source-not-found.png" rel="shadowbox[sbpost-1767];player=img;" title="&quot;Source not found&quot; error in Eclipse"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=aff27d40442096b905248f8217afc7508df51a8b_500x500_resize_if_larger" title="&quot;Source not found&quot; error in Eclipse" alt="&quot;Source not found&quot; error in Eclipse" width="500" height="243"/></a></div>
<p>To solve this problem you had to manually download the whole Android source code (which contains much more than just the Java source code files) and then manually assemble a source files directory from the Java files scattered throughout the Android source tree. Very tedious and certainly not very simple.</p>
<h2 id="the_solution">The Solution</h2>
<p>Fortunately, there is a Google Code project named &#8220;adt-addons&#8221; aiming to solve this problem. The project actually consists of several Eclipse plugins, but the one you want is called &#8220;Android Sources&#8221;. You can either search the instructions on the project page, or follow them (nicely formatted) here.</p>
<p>Basically what you need is to install the &#8220;Android Sources&#8221; plugin (about <em>170 MB</em>). Here&#8217;s the update URL:</p>
<p class="indented"><a href="http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/" target="_blank">http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/</a></p>
<p>After installing the plugin, simply restart Eclipse and the Android source code is already attached to the Android classes.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/source-found.png" rel="shadowbox[sbpost-1767];player=img;" title="Sources found for Android classes"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=cc1f35a156ddbf4751b6e2e6368f32b0abf635c0_500x500_resize_if_larger" title="Sources found for Android classes" alt="Sources found for Android classes" width="500" height="252"/></a></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/7v_eISdPmZ8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/14/android-source-code-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/14/android-source-code-in-eclipse/</feedburner:origLink></item>
		<item>
		<title>Eclipse Plugins</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/OqzIJ-g16RQ/</link>
		<comments>http://manski.net/2011/11/11/eclipse-plugins/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 09:14:58 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Pinned]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[eclipse]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1764</guid>
		<description><![CDATA[This is just a note to my self of what Eclipse plugins I&#8217;ll use. This list may, however, also be useful to you. Subclipse: Subversion support MercurialEclipse: Mercurial support ExploreFS: This plugin allows you to open a file in Windows Explorer/Finder through the context menu. CheckStyle: This plugins allows you define more precise rules for [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->This is just a note to my self of what <a href="http://eclipse.org" target="_blank">Eclipse</a> plugins I&#8217;ll use. This list may, however, also be useful to you.</p>
<ul>
<li class="first-item"><strong><a href="http://subclipse.tigris.org/" target="_blank">Subclipse</a>:</strong> Subversion support</li>
<li><strong><a href="http://www.javaforge.com/project/HGE" target="_blank">MercurialEclipse</a>:</strong> Mercurial support</li>
<li><strong><a href="http://www.junginger.biz/eclipse/index.html" target="_blank">ExploreFS</a>:</strong> This plugin allows you to open a file in Windows Explorer/Finder through the context menu.</li>
<li><strong><a href="http://eclipse-cs.sourceforge.net/downloads.html" target="_blank">CheckStyle</a>:</strong> This plugins allows you define more precise rules for your code style. If a rule is violated, a warning is issued.</li>
<li class="last-item">
<p><strong><a href="http://testng.org/doc/eclipse.html" target="_blank">TestNG</a>:</strong> Unit testing framework (much like JUnit)</p>
</li>
</ul>
<p>To see what plugins have already been installed, go to <strong>Help</strong> &#8211;> <strong>Install new software&#8230;</strong> and click on <strong>What is <span class="underline">already installed</span>?</strong> at the bottom of the dialog.</p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/OqzIJ-g16RQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/11/eclipse-plugins/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/11/eclipse-plugins/</feedburner:origLink></item>
		<item>
		<title>About: Jobs</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/iO7Vuu2gIr0/</link>
		<comments>http://manski.net/2011/11/09/about-jobs/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 18:55:34 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Funny Stuff]]></category>
		<category><![CDATA[Private Blog]]></category>
		<category><![CDATA[Tech Blog]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1758</guid>
		<description />
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->
<div class="align-center image-align-center"><img src="http://manski.net/wordpress/wp-content/uploads/2011/11/Jobs.jpg" title="About Jobs" alt="About Jobs"/></div>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/iO7Vuu2gIr0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/09/about-jobs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/09/about-jobs/</feedburner:origLink></item>
		<item>
		<title>Projects in Visual C++ 2010 – Part 3: Precompiled Headers</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/JX7mhe5HNaY/</link>
		<comments>http://manski.net/2011/11/09/precompiled-headers/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 12:53:47 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[visual c++]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1747</guid>
		<description><![CDATA[In this part of the &#8220;Projects in Visual C++ 2010&#8243; mini series another important aspect of C++ programming is explain: precompiled headers. Precompiled headers (or precompiled header files) in many cases significantly reduce the time needed to compile a project. Here at work I have a C++ project with about 50 .cpp files in it. [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->In this part of the &#8220;Projects in Visual C++ 2010&#8243; mini series another important aspect of C++ programming is explain: <em>precompiled headers</em>. Precompiled headers (or precompiled header files) in many cases significantly reduce the time needed to compile a project. </p>
<p>Here at work I have a C++ project with about 50 <code>.cpp</code> files in it. The project uses the Qt library and all files only include the absolute minimum of header files required. Without precompiled headers, compiling the project takes about 56 seconds. <em>With</em> precompiled headers, the compile time goes down to about 7 seconds. That&#8217;s eight times faster.</p>
<p><strong>Related Articles:</strong></p>
<ul>
<li class="first-item"><a href="http://manski.net/2011/11/09/creating-a-dll-project/">Projects in Visual C++ 2010 &#8211; Part 1: Creating a DLL project</a></li>
<li class="last-item">
<p><a href="http://manski.net/2011/11/09/project-dependencies-in-visual-c/">Projects in Visual C++ 2010 &#8211; Part 2: Project Dependencies</a></p>
</li>
</ul>
<p><span id="more-1747"></span></p>
<p>The procedure described here only applies to Visual C++ (if I&#8217;m correct since version 6.0). However, other C++ compilers may provide similar functionality.</p>
<h2 id="the_problem">The Problem</h2>
<p>The problem precompiled headers solve is the long compile time when compiling a C++ project. (Note that other languages such as Java or C# don&#8217;t have this problem.) The underlying problem is the <code>#include &lt;...&gt;</code> statement. This simply copies the whole content of the file included into the source file. While one header file may not be that big, it may also include other header files. When using a framework (such as Qt or even Win32), one include statement will import a huge amount of source code. And this huge amount is what takes so long when compiling a C++ project. Furthermore, if this huge amount gets included in every source code file, all of it has to be compiled again for every source file.</p>
<p>So, the idea is to (pre)compile these huge amount of source code <em>once</em>, and then reuse it in every source code file of the project. This drastically reduces the compile time required.</p>
<h2 id="specifying_the_precompiled_header_.28stdafx.h.29">Specifying the precompiled header (stdafx.h)</h2>
<p>To be able to use a precompiled header in Visual C++, one first needs to specify which headers shall be precompiled. Visual C++ only allows one precompiled header file per project. By default, it&#8217;s called <strong>stdafx.h</strong>. This name can be changed in the project settings under &#8220;C++&#8221; &#8211;> &#8220;Precompiled Headers&#8221; &#8211;> &#8220;Precompiled Header File&#8221;.</p>
<p>The limitation that only one precompiled header is allowed is no real limitation because you can include any header file from within the precompiled header. For example, a precompiled header may look like this (for using the Qt framework):</p>
<pre class="code">#pragma message(&quot;Compiling precompiled headers.\n&quot;)

#include &lt;QtCore&gt;
#include &lt;QtXml&gt;
#include &lt;QtGui&gt;</pre>
<p>So when this header is precompiled, all included headers will be precompiled as well. Thus, the more of the headers you use in your project are specified here, the faster the other files in the project compile. Note that including more header files than are actually used is not a problem.</p>
<p>You may also note the <code>#pragma</code> statement on the first line. This is just &#8220;helper statement&#8221;. With it, every time the precompiled header is compiled, the specified message will be printed to the build output. If you see this message twice or more while compiling a single project, something is wrong. (In most cases you won&#8217;t see the message at all because the precompiled header is already compiled.)</p>
<h2 id="using_the_precompiled_header">Using the Precompiled Header</h2>
<p>Whether to use a precompiled header or not can be specified per project as well as per file. When you want to use a precompiled header in a project, you usually say &#8220;Use&#8221; for the whole project and then exclude certain <code>.cpp</code> file that shall not use the precompiled header. Both options are in the same section &#8211; it just depends on whether you open the project settings or the file settings (both being available through their context menus).</p>
<p>To enable precompiled headers in a project (or file), open the project settings (or file settings) and select &#8220;Use&#8221; under &#8220;C++&#8221; &#8211;> &#8220;Precompiled Headers&#8221; &#8211;> &#8220;Precompiled Header&#8221;. Also make sure, that you&#8217;ve selected &#8220;All Configurations&#8221; from the &#8220;Configuration&#8221; dropdown field. (Note that the option &#8220;Create&#8221; will be used <a href="#compiling_the_header">below</a>.)</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/enable-precompiled-headers.png" rel="shadowbox[sbpost-1747];player=img;" title="Enabling precompiled headers on project level"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=5a2534a2d5dc02a49d408053c499bd219e6df09c_300x300_resize_if_larger" title="Enabling precompiled headers on project level" alt="Enabling precompiled headers on project level" width="300" height="108"/></a></div>
<p>The next thing you need to do is to <code>#include &quot;...&quot;</code> the precompiled header file in every source file (<code>.cpp</code>). You shouldn&#8217;t (can&#8217;t?) include it in the header files (<code>.h</code>) but only in the <code>.cpp</code> file. Also, the include statement must be <em>the first statement</em> in the file (only comments or whitespace is allowed above it). This is because Visual C++ assumes that everything before the include statement is already compiled.</p>
<p>So the beginning of a <code>.cpp</code> file in your project may look like this:</p>
<pre class="code">// File with some fancy functions.
#include &quot;stdafx.h&quot;
#include &quot;myfancefunctions.h&quot;
...</pre>
<p>Note that the name of the precompiled header file is the one you specified above (or &#8220;stdafx.h&#8221; by default).</p>
<h2 id="compiling_the_header">Compiling the Header</h2>
<p>By now, we&#8217;ve specified which headers are to be compile and where these headers will be used. The last step is to actually compile the precompiled header. Without this you&#8217;ll get a &#8220;Cannot open precompiled header file&#8221; error message when compiling the project.</p>
<p>For this you need to add a new <code>.cpp</code> file to your project. By convention, it has the same name as the precompiled header but that&#8217;s no strict requirement. This file only needs to contain one statement:</p>
<pre class="code">// stdafx.cpp
#include &quot;stdafx.h&quot;</pre>
<p>Next, you need to go to the <em>file&#8217;s</em> settings (via context menu) and change the value of &#8220;Precompiled Header&#8221; from &#8220;Use&#8221; to &#8220;Create&#8221;.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/creating-precompiled-header.png" rel="shadowbox[sbpost-1747];player=img;" title="Setting options for creating a precompiled header"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=0be21cdcfe2e9c614f1ff4c37573f61649680bfe_300x300_resize_if_larger" title="Setting options for creating a precompiled header" alt="Setting options for creating a precompiled header" width="300" height="92"/></a></div>
<p>That&#8217;s it. Now, when compiling the project again for the first time, the precompiled header will be created. After that, compiling the other source files should be significantly faster than before. Also the precompiled header will only be compiled on the first run. After that it won&#8217;t be compiled again (which would somehow defeat its purpose) unless either the &#8220;stdafx.cpp&#8221; or &#8220;stdafx.h&#8221; file is modified.</p>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/JX7mhe5HNaY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/09/precompiled-headers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/09/precompiled-headers/</feedburner:origLink></item>
		<item>
		<title>Projects in Visual C++ 2010 – Part 2: Project Dependencies</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/VS4tC913u3o/</link>
		<comments>http://manski.net/2011/11/09/project-dependencies-in-visual-c/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 10:44:07 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[dll]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[visual c++]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1722</guid>
		<description><![CDATA[This article is the second part of the subprojects mini series. The first part was about creating a DLL project. This part will show how to use a DLL library project in another project. Referencing a library in C++ (or, more specific, with Visual C++) is somewhat cumbersome &#8211; or should I say, used to [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->This article is the second part of the subprojects mini series. The first part was about <a href="http://manski.net/2011/11/09/creating-a-dll-project/">creating a DLL project</a>. This part will show how to use a DLL library project in another project.</p>
<p>Referencing a library in C++ (or, more specific, with Visual C++) is somewhat cumbersome &#8211; or should I say, <em>used to be</em> somewhat cumbersome. Fortunately, with the release of <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express" target="_blank">Visual C++ 2010</a> this has been greatly simplified. This article first shows the old way and then describes the new (simple) way.</p>
<p><strong>Related Articles:</strong></p>
<ul>
<li class="first-item"><a href="http://manski.net/2011/11/09/creating-a-dll-project/">Projects in Visual C++ 2010 &#8211; Part 1: Creating a DLL project</a></li>
<li class="last-item">
<p><a href="http://manski.net/2011/11/09/precompiled-headers/">Projects in Visual C++ 2010 &#8211; Part 3: Precompiled Headers</a></p>
</li>
</ul>
<p><span id="more-1722"></span></p>
<h2 id="the_setup">The setup</h2>
<p>For the discussion of this article assume we have two projects:</p>
<ul>
<li class="first-item">MyLibrary</li>
<li class="last-item">
<p>MyProgram (which uses MyLibrary)</p>
</li>
</ul>
<p>The project &#8220;MyLibrary&#8221; compiles into a DLL library (although a static <code>.lib</code> might also work) and &#8220;MyProgram&#8221; is just a regular <code>.exe</code> project. </p>
<h3 id="the_code.3A_mylibrary">The Code: MyLibrary</h3>
<p>&#8220;MyLibrary&#8221; uses the code from the first part of this series. It provides a class called <code>PrintableInt</code> which wraps an integer and provides a method to convert it into a string.</p>
<pre class="code">// PrintableInt.h
#pragma once

#include &lt;string&gt;

#ifdef COMPILE_MYLIBRARY
  #define MYLIBRARY_EXPORT __declspec(dllexport)
#else
  #define MYLIBRARY_EXPORT __declspec(dllimport)
#endif

class MYLIBRARY_EXPORT PrintableInt {
public:
  // Constructor
  PrintableInt(int value);
  // Converts the int into a string.
  std::string toString() const;
private:
  int m_value;
};</pre>
<pre class="code">// PrintableInt.cpp
#include &quot;stdafx.h&quot;
#include &quot;PrintableInt.h&quot;
#include &lt;sstream&gt;

PrintableInt::PrintableInt(int value) {
  m_value = value;
}

std::string PrintableInt::toString() const {
  std::ostringstream builder;
  builder &lt;&lt; m_value;
  return builder.str();
}</pre>
<p>Again, this (and the project &#8220;MyProgram&#8221; as well) use a precompiled header file named &#8220;stdafx.h&#8221;. Precompiled headers are explained in <a href="http://manski.net/2011/11/09/precompiled-headers/">another article</a>.</p>
<h3 id="the_code.3A_myprogram">The Code: MyProgram</h3>
<p>The project &#8220;MyProgram&#8221; is a &#8220;Win32 Console Application&#8221; project and just contains some test code in its main function:</p>
<pre class="code">#include &quot;stdafx.h&quot;
#include &lt;iostream&gt;
#include &quot;PrintableInt.h&quot;

int _tmain(int argc, _TCHAR* argv[]) {
  PrintableInt test(5);
  std::cout &lt;&lt; test.toString() &lt;&lt; std::endl;
  return 0;
}</pre>
<p>This simply prints a &#8220;5&#8243; on the console.</p>
<h2 id="the_old_way">The old way</h2>
<p>In Visual C++ 2008 or earlier, to define a project dependency several steps needed to be executed (in no particular order). These steps are described below. Note that these steps still work in Visual C++ 2010.</p>
<h3 id="specify_build_order">Step: Specify Build Order</h3>
<p>To determine the order in which the projects of the solution will be built, project dependencies need to be specified. This way dependencies will be built before the projects that use them.</p>
<p>To specify a dependency, select &#8220;Project Dependencies&#8230;&#8221; from a project&#8217;s context menu. Then check all projects the current project depends on.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/project-dependencies.png" rel="shadowbox[sbpost-1722];player=img;" title="Specifying project dependencies the old way."><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=3fab6f2a0e566c8fc160520ca28183a750256e36_300x300_resize_if_larger" title="Specifying project dependencies the old way." alt="Specifying project dependencies the old way." width="300" height="278"/></a></div>
<h3 id="specify_include_path">Step: Specify Include Path</h3>
<p>You also need to specify to path where to find the header files of the library project you want to use. This makes it possible to specify a header file by just using <code>&quot;PrintableInt.h&quot;</code> instead of <code>&quot;../MyLibrary/PrintableInt.h&quot;</code>.</p>
<p>To do this, open the settings of the project that wants to use the library and specify the path under &#8220;Additional Include Directories&#8221;. You should also make sure that you&#8217;ve selected &#8220;All Configurations&#8221; from the &#8220;Configuration&#8221; dropdown field (see screenshot).</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/specifying-include-path.png" rel="shadowbox[sbpost-1722];player=img;" title="Specifying the include path for using a library project"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=59fdd2722ed8400518069b625219845f3f1bc05d_300x300_resize_if_larger" title="Specifying the include path for using a library project" alt="Specifying the include path for using a library project" width="300" height="99"/></a></div>
<h3 id="step.3A_specify_lib_file">Step: Specify Lib File</h3>
<p>The last step is to specify the path to the <code>.lib</code> file of the library project. Note that even DLL projects will create a <code>.lib</code> file so that your project can link against the DLL automatically.</p>
<p>To specify the <code>.lib</code> file, again go to the project settings, but this time go to <code>Linker</code> &#8211;> <code>Input</code> and specify the file under &#8220;Additional Dependencies&#8221;. Note that you&#8217;ll need (or probably want) to specify different <code>.lib</code> files for the &#8220;Debug&#8221; and the &#8220;Release&#8221; configuration. The screenshot below shows the value for the &#8220;Debug&#8221; configuration.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/specify-lib-file.png" rel="shadowbox[sbpost-1722];player=img;" title="Specifying the .lib file for the dependency"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=c1ebc982d7c6706515fb4aaaf7dbcfab094c84d1_300x300_resize_if_larger" title="Specifying the .lib file for the dependency" alt="Specifying the .lib file for the dependency" width="300" height="111"/></a></div>
<h2 id="the_new_way">The New Way</h2>
<p>Since Visual C++ 2010 there is a new, simpler way to specify a project dependency. With this way, unfortunately you still need to specify the include path to the library project (see <a href="#specify_include_path">above</a>) but all other steps are simplified.</p>
<p>To reference a dependency the new way, choose &#8220;References&#8230;&#8221; from the project&#8217;s context menu. This will open up the project settings with the section &#8220;Framework and References&#8221; being selected. There click on &#8220;Add New Reference&#8230;&#8221; and then select the project you want to use in the current project.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/add-new-reference.png" rel="shadowbox[sbpost-1722];player=img;" title="Adding a project dependency the new way"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=ad7f11fcbaf12b0c2cd5230cb5aaf565486a58a4_300x300_resize_if_larger" title="Adding a project dependency the new way" alt="Adding a project dependency the new way" width="300" height="212"/></a></div>
<p>And that&#8217;s it. Your project should now compile.</p>
<p>Besides being easier to use, the new way has also another advantage: The information about project dependencies are now stored in the project file instead of the solution file (which is the case with the way described in <a href="#specify_build_order">Step: Specify Build Order</a>). This way you can use a library project that has some dependencies itself in several different solutions and always have the dependencies already set up correctly. (With the old way you had to recreate the dependencies for each solution manually.)</p>
<p><em>Note:</em> There are two options &#8211; available in the project settings &#8211; that influence how these references work. Both can be found under &#8220;Linker&#8221; &#8211;> &#8220;General&#8221;:</p>
<ul>
<li class="first-item"><em>Ignore Import Library:</em> This is specified in the library project. When this is set, the <code>.lib</code> file generated by the project won&#8217;t be used automatically by projects that depend on it. (Default: No)</li>
<li class="last-item">
<p><em>Link Library Dependencies:</em> This is the opposite of the other option. It&#8217;s specified on the project that uses other projects. If set to &#8220;No&#8221;, dependencies won&#8217;t be linked automatically. (Default: Yes)</p>
</li>
</ul>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/automatic-linking-option.png" rel="shadowbox[sbpost-1722];player=img;" title="Options influencing automatic linking"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=ad0348c96040a61645684c3ef02a8d4c87cf9a58_300x300_resize_if_larger" title="Options influencing automatic linking" alt="Options influencing automatic linking" width="300" height="114"/></a></div>
<h3 id="what.27s_not_working">What&#8217;s not working</h3>
<p>Unfortunately, there&#8217;s one details that make the new way a little more difficult to use again. *sigh* The problem: Visual Studio won&#8217;t copy the DLL files of the referenced libraries to the output folder automatically. Here&#8217;s what <a href="http://msdn.microsoft.com/en-us/library/ms235636%28v=vs.80%29.aspx" target="_blank">the documentation</a> says about that:</p>
<blockquote><p> Dynamic link libraries are not loaded by the executable until runtime. You must tell the system where to locate <strong>MathFuncsDll.dll</strong>. This is done using the <strong>PATH</strong> environment variable. To do this, from the <strong>Property Pages</strong> dialog, expand the <strong>Configuration Properties</strong> node and select <strong>Debugging</strong>. Next to <strong>Environment</strong>, type in the following: <code>PATH=&lt;path to MathFuncsDll.dll file&gt;</code>, where <code>&lt;path to MathFuncsDll.dll file&gt;</code> is replaced with the actual location of <strong>MathFuncsDll.dll</strong>. Press <strong>OK</strong> to save all the changes made.
</p></blockquote>
<p>There are several possible solutions for this problem (although, theoretically, this problem shouldn&#8217;t arise in the first place):</p>
<ul>
<li class="first-item">Set the output directory to be the same as the directory where the DLL files are compiled to. (recommended)</li>
<li class="last-item">
<p>Use the &#8220;PATH&#8221; like describes in the documentation.</p>
</li>
</ul>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/VS4tC913u3o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/09/project-dependencies-in-visual-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/09/project-dependencies-in-visual-c/</feedburner:origLink></item>
		<item>
		<title>Projects in Visual C++ 2010 – Part 1: Creating a DLL project</title>
		<link>http://feedproxy.google.com/~r/ManskisBlog/~3/YYiPZ8rnMRI/</link>
		<comments>http://manski.net/2011/11/09/creating-a-dll-project/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 09:39:23 +0000</pubDate>
		<dc:creator>Manski</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[dll]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[visual c++]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://manski.net/?p=1725</guid>
		<description><![CDATA[When you write software, you often/sometimes divide your project into several subprojects. This mini series describes how to do this with Visual C++ 2010 (but this first part also applies to earlier versions). We start with creating a library project in form of a DLL. Related articles: Projects in Visual C++ 2010 &#8211; Part 2: [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2012-01-30 14:44:07 -->When you write software, you often/sometimes divide your project into several subprojects. This mini series describes how to do this with <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express" target="_blank">Visual C++ 2010</a> (but this first part also applies to earlier versions). We start with creating a library project in form of a DLL.</p>
<p><strong>Related articles:</strong></p>
<ul>
<li class="first-item"><a href="http://manski.net/2011/11/09/project-dependencies-in-visual-c/">Projects in Visual C++ 2010 &#8211; Part 2: Project Dependencies</a></li>
<li class="last-item">
<p><a href="http://manski.net/2011/11/09/precompiled-headers/">Projects in Visual C++ 2010 &#8211; Part 3: Precompiled Headers</a></p>
</li>
</ul>
<p><span id="more-1725"></span></p>
<h2 id="library_projects">Library Projects</h2>
<p>Library projects are projects that usually contain reusable functions or classes. They&#8217;re a great way of structuring a big project. In Visual C++ (or in C++ in general) there are two types of libraries: static libraries and dynamic libraries.</p>
<p>Static libraries (<code>.lib</code>) are &#8220;merged&#8221; into the final <code>.exe</code> file when the whole project is compiled. Therefore, for the outside user, this library type isn&#8217;t visible.</p>
<p>Dynamic libraries (<code>.dll</code>) on the other hand remain separate from the final <code>.exe</code> file in their own files. (See more information <a href="http://msdn.microsoft.com/en-us/library/1ez7dh12.aspx" target="_blank">here</a>.)</p>
<p>In this article we&#8217;ll create a <em>dynamic</em> library.</p>
<h2 id="creating_the_library_project">Creating the Library Project</h2>
<p>To create a library project in Visual C++ 2010 (that is a part of Visual Studio 2010) in an <em>existing</em> solution, choose <code>Add</code> &#8211;> <code>New Project...</code> from the solution&#8217;s context menu in the &#8220;Solution Explorer&#8221; window.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/add-new-project.png" rel="shadowbox[sbpost-1725];player=img;" title="Adding a new project by using the context menu"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=c8e49390825d0f0ed5f746f1f953c2c78dc2279a_300x300_resize_if_larger" title="Adding a new project by using the context menu" alt="Adding a new project by using the context menu" width="300" height="205"/></a></div>
<p>Alternatively you can create a new solution by using <code>File</code> &#8211;> <code>New</code> &#8211;> <code>Project...</code>. Either way will open up the &#8220;Add New Project&#8221; dialog. Here you choose &#8220;Class Library&#8221; (in section <code>Other Languages</code> &#8211;> <code>Visual C++</code>) and specify a new for the project. This name will also be the name of the DLL file.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/create-new-library-project.png" rel="shadowbox[sbpost-1725];player=img;" title="Creating a new class library"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=cc067ea8d007f4f9608ad92a31b4e3776bcf45cd_300x300_resize_if_larger" title="Creating a new class library" alt="Creating a new class library" width="300" height="209"/></a></div>
<p>After hitting &#8220;Ok&#8221;, your new class library project will be created. By default, it&#8217;ll create a dynamic library. To make it a <em>static</em> library project, head to the project&#8217;s settings (available through the project&#8217;s context menu) and set <code>Configuration Type</code> to <code>Static library (.lib)</code> (see screenshot).</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/library-project-settings.png" rel="shadowbox[sbpost-1725];player=img;" title="A static library project with CLR support disabled"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=55811c875353678781264a8d8765f5ced322b6ab_300x300_resize_if_larger" title="A static library project with CLR support disabled" alt="A static library project with CLR support disabled" width="300" height="213"/></a></div>
<p>You may also want to review the setting <code>Common Language Runtime Support</code>. If enabled (switch <code>/clr</code>), this will allow you to create .NET classes in this project. For a pure C++ project, however, you may want to disable CLR support (as shown in the screenshot above).</p>
<h2 id="writing_a_reusable_class">Writing a Reusable Class</h2>
<p>The purpose of a library is to provide (potentially) reusable functions and/or classes. So, let&#8217;s create a simple reusable class. </p>
<p>The new class is called <code>PrintableInt</code>. It wraps an integer and provides a <code>toString()</code> method that will convert the integer into a string.</p>
<pre class="code">// PrintableInt.h
#pragma once

#include &lt;string&gt;

class PrintableInt {
public:
  // Constructor
  PrintableInt(int value);
  // Converts the int into a string.
  std::string toString() const;
private:
  int m_value;
};</pre>
<pre class="code">// PrintableInt.cpp
#include &quot;stdafx.h&quot;
#include &quot;PrintableInt.h&quot;
#include &lt;sstream&gt;

PrintableInt::PrintableInt(int value) {
  m_value = value;
}

std::string PrintableInt::toString() const {
  std::ostringstream builder;
  builder &lt;&lt; m_value;
  return builder.str();
}</pre>
<p>The library should now compile without problems.</p>
<p>Note that the <code>.cpp</code> file include a file called <code>stdafx.h</code>. This is a so called &#8220;precompiled header file&#8221;. This feature is explained in <a href="http://manski.net/2011/11/09/precompiled-headers/">another article</a>. It should, however, work out-of-the-box in your project.</p>
<h2 id="exporting_classes">Exporting Classes</h2>
<p>By default, all classes and functions defined in a library project are &#8220;internal&#8221;. That means that another project can&#8217;t use them. To change this, classes (or function) that are to be used by other project must be &#8220;exported&#8221;. In Visual C++ you do this with <code>__declspec(dllexport)</code>.</p>
<p>Now, you could specify the export like this:</p>
<pre class="code">// PrintableInt.h
class __declspec(dllexport) PrintableInt {
  ...
}</pre>
<p>However, since all projects using this library will most likely use the same header file (<code>PrintableInt.h</code>), this would mean that even the &#8220;using&#8221; projects would export the class as well. Of course, this is not what we want. Instead you create a macro and use it like this:</p>
<pre class="code">// PrintableInt.h

#ifdef COMPILE_MYLIBRARY
  #define MYLIBRARY_EXPORT __declspec(dllexport)
#else
  #define MYLIBRARY_EXPORT __declspec(dllimport)
#endif

class MYLIBRARY_EXPORT PrintableInt {
  ...
}</pre>
<p>For this to work, you add the preprocessor definition <code>COMPILE_MYLIBRARY</code> to the library project (but <em>not</em> to the projects using the library). This way <code>MYLIBRARY_EXPORT</code> will be replaced by <code>__declspec(dllexport)</code> when compiling the library project and by <code>__declspec(dllimport)</code> when using the project (from another project). To specify this preprocessor, go to the library project&#8217;s settings and enter the name <code>COMPILE_MYLIBRARY</code> in the field &#8220;Preprocessor Definitions&#8221;. You should also make sure to select &#8220;All Configuration&#8221; from the &#8220;Configuration&#8221; dropdown field (see screenshot) so that this definition gets added to the Debug <em>and</em> Release configuration.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/preprocessor-definition.png" rel="shadowbox[sbpost-1725];player=img;" title="Specifying a preprocessor definition"><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=788c46020443dae26996b090fbae13d1bf85f72b_300x300_resize_if_larger" title="Specifying a preprocessor definition" alt="Specifying a preprocessor definition" width="300" height="91"/></a></div>
<p><em>Note:</em> The keyword <code>__declspec(...)</code> is a Microsoft specific extension to C++ (see <a href="http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx" target="_blank">here</a>). So it only works in Visual C++. There is an alternative (more portable?) way to specify which classes/functions are to be exported. For this, a &#8220;Module-Definition File&#8221; (<code>.def</code>) needs to be created. However, creating such a file is more tedious than specifying the export statement directly in the code. For more information, see <a href="http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9855" target="_blank">this article</a>.</p>
<p>Now, when you compile the library project, an additional <code>.lib</code> file will be created. This file is used to import the exported classes/functions in another project. (If you don&#8217;t export anything, the file won&#8217;t be created.) How to do this, is explained in <a href="http://manski.net/2011/11/09/project-dependencies-in-visual-c/">part two of this mini series</a>.</p>
<h2 id="dllimport_necessary.3F">dllimport necessary?</h2>
<p>The example above specifies that <code>__declspec(dllimport)</code> is to be used when using the library project. You may notice that this isn&#8217;t necessary in the above example. However, it doesn&#8217;t hurt either.</p>
<p>This statement becomes important though when you export templated classes. To demonstrate this, change <code>PrintableInt</code> like this:</p>
<pre class="code">// PrintableInt.h
#pragma once

#include &lt;string&gt;

#ifdef COMPILE_MYLIBRARY
  #define MYLIBRARY_EXPORT __declspec(dllexport)
#else
  #define MYLIBRARY_EXPORT //__declspec(dllimport)
#endif

template&lt;int T&gt;
class MYLIBRARY_EXPORT PrintableInt {
public:
  // Constructor
  PrintableInt(int value);
  // Converts the int into a string.
  std::string toString() const;
private:
  int m_value;
};</pre>
<pre class="code">// PrintableInt.cpp
#include &quot;stdafx.h&quot;
#include &quot;PrintableInt.h&quot;
#include &lt;sstream&gt;

template&lt;int T&gt;
PrintableInt&lt;T&gt;::PrintableInt(int value) {
  m_value = value;
}

template&lt;int T&gt;
std::string PrintableInt&lt;T&gt;::toString() const {
  std::ostringstream builder;
  builder &lt;&lt; m_value;
  return builder.str();
}</pre>
<p>This adds the type parameter <code>T</code> to the class. Note that <code>__declspec(dllimport)</code> has been commented out to demonstrate the problem.</p>
<p><em>Note:</em> The type parameter <code>T</code> serves no purpose in this implementation. It&#8217;s just there to demonstrate the problem.</p>
<p>Now, assume another project using the library project like this:</p>
<pre class="code">#include &lt;iostream&gt;
#include &quot;PrintableInt.h&quot;

int _tmain(int argc, _TCHAR* argv[]) {
  PrintableInt&lt;6&gt; test(5);
  std::cout &lt;&lt; test.toString() &lt;&lt; std::endl;
  return 0;
}</pre>
<p>Without &#8220;dllimport&#8221; compiling this project will result in (rather cryptic) linker errors &#8211; namely &#8220;unresolved external symbol&#8221;. Uncommenting <code>__declspec(dllimport)</code> in <code>PrintableInt.h</code> again solves this problem.</p>
<div class="align-center image-align-center"><a href="http://manski.net/wordpress/wp-content/uploads/2011/11/unresolved-symbols.png" rel="shadowbox[sbpost-1725];player=img;" title="Error window listing &quot;unresolved external symbol&quot; errors."><img src="http://manski.net/wordpress/wp-content/plugins/blogtext/api/thumbnail/do.php?id=82a382464ba1286b937acc1a118d4344142330e0_300x300_resize_if_larger" title="Error window listing &quot;unresolved external symbol&quot; errors." alt="Error window listing &quot;unresolved external symbol&quot; errors." width="300" height="73"/></a></div>
<p><a href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=274673" rel="tag" style="display:none">CodeProject</a></p>
<img src="http://feeds.feedburner.com/~r/ManskisBlog/~4/YYiPZ8rnMRI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://manski.net/2011/11/09/creating-a-dll-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://manski.net/2011/11/09/creating-a-dll-project/</feedburner:origLink></item>
	</channel>
</rss>

