CINXE.COM
HackingWesnoth - The Battle for Wesnoth Wiki
<!DOCTYPE html> <html class="client-nojs" lang="en" dir="ltr"> <head> <meta charset="UTF-8"/> <title>HackingWesnoth - The Battle for Wesnoth Wiki</title> <script>document.documentElement.className = document.documentElement.className.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );</script> <script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"HackingWesnoth","wgTitle":"HackingWesnoth","wgCurRevisionId":50375,"wgRevisionId":50375,"wgArticleId":1685,"wgIsArticle":true,"wgIsRedirect":false,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Development"],"wgBreakFrames":false,"wgPageContentLanguage":"en","wgPageContentModel":"wikitext","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"dmy","wgMonthNames":["","January","February","March","April","May","June","July","August","September","October","November","December"],"wgMonthNamesShort":["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"wgRelevantPageName":"HackingWesnoth","wgRelevantArticleId":1685,"wgRequestId":"6399d3dc96600f7ed970a2b4","wgIsProbablyEditable":false,"wgRelevantPageIsProbablyEditable":false,"wgRestrictionEdit":[],"wgRestrictionMove":[],"wgWikiEditorEnabledModules":[]});mw.loader.state({"site.styles":"ready","noscript":"ready","user.styles":"ready","user":"ready","user.options":"ready","user.tokens":"loading","ext.CookieWarning.styles":"ready","mediawiki.legacy.shared":"ready","mediawiki.legacy.commonPrint":"ready","mediawiki.sectionAnchor":"ready"});mw.loader.implement("user.tokens@15y0z4f",function($,jQuery,require,module){/*@nomin*/mw.user.tokens.set({"editToken":"+\\","patrolToken":"+\\","watchToken":"+\\","csrfToken":"+\\"}); });mw.loader.load(["site","mediawiki.page.startup","mediawiki.user","mediawiki.hidpi","mediawiki.page.ready","mediawiki.toc","mediawiki.searchSuggest","ext.CookieWarning","skins.wesmere.js"]);});</script> <link rel="stylesheet" href="/load.php?debug=false&lang=en&modules=ext.CookieWarning.styles%7Cmediawiki.legacy.commonPrint%2Cshared%7Cmediawiki.sectionAnchor&only=styles&skin=Wesmere"/> <script async="" src="/load.php?debug=false&lang=en&modules=startup&only=scripts&skin=Wesmere"></script> <meta name="ResourceLoaderDynamicStyles" content=""/> <link rel="stylesheet" href="/load.php?debug=false&lang=en&modules=site.styles&only=styles&skin=Wesmere"/> <meta name="generator" content="MediaWiki 1.31.16"/> <meta name="description" content="This page is designed to be a guide for aspiring Wesnoth programmers on what they need to do to be able to productively contribute to the Wesnoth code base."/> <link rel="shortcut icon" href="/favicon.ico"/> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch_desc.php" title="The Battle for Wesnoth Wiki (en)"/> <link rel="EditURI" type="application/rsd+xml" href="https://wiki.wesnoth.org/api.php?action=rsd"/> <link rel="alternate" type="application/atom+xml" title="The Battle for Wesnoth Wiki Atom feed" href="/index.php?title=Special:RecentChanges&feed=atom"/> <meta name="viewport" content="width=device-width,initial-scale=1" /> <link rel="stylesheet" type="text/css" href="https://www.wesnoth.org/wesmere/css/wesmere-1.2.0.css" /> <script src="https://www.wesnoth.org/wesmere/js/modernizr.js"></script> <link rel="apple-touch-icon" type="image/png" href="https://www.wesnoth.org/wesmere/img/apple-touch-icon.png" sizes="180x180" /> <link rel="icon" type="image/png" href="https://www.wesnoth.org/wesmere/img/favicon-32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="https://www.wesnoth.org/wesmere/img/favicon-16.png" sizes="16x16" /> <meta name="theme-color" content="#0f1421" /> <!--[if lt IE 9]><script src="/load.php?debug=false&lang=en&modules=html5shiv&only=scripts&skin=Wesmere&sync=1"></script><![endif]--> </head> <body class="mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-HackingWesnoth rootpage-HackingWesnoth skin-Wesmere action-view"><div class="mw-cookiewarning-container"><div class="mw-cookiewarning-text"><span>Cookies help us deliver our services. By using our services, you agree to our use of cookies.</span><form method="POST"><input name="disablecookiewarning" class="mw-cookiewarning-dismiss" type="submit" value="OK"/></form></div></div> <div id="main"> <div id="nav" role="banner"> <div class="centerbox"> <div id="logo"> <a href="https://www.wesnoth.org/" aria-label="Wesnoth logo"></a> </div> <ul id="navlinks"> <li><a href="https://www.wesnoth.org/">Home</a></li> <li><a href="https://forums.wesnoth.org/viewforum.php?f=62">News</a></li> <li><a href="https://wiki.wesnoth.org/Play">Play</a></li> <li><a href="https://wiki.wesnoth.org/Create">Create</a></li> <li><a href="https://forums.wesnoth.org/">Forums</a></li> <li><a href="https://wiki.wesnoth.org/Project">About</a></li> </ul> <div id="sitesearch" role="search"> <form method="get" action="/index.php"> <input id="searchbox" type="search" name="search" placeholder="Search" value="" title="Search this wiki [Alt+Shift+f]" accesskey="f" /> <span id="searchbox-controls"> <button id="search-go" class="search-button" type="submit" title="Search"> <i class="search-icon" aria-hidden="true"></i> <span class="sr-label">Search this wiki</span> </button> </span> </form> </div> <div class="reset"></div> </div> </div> <div id="content" class="mw-content" role="main"> <a id="top"></a> <div id="wm-wiki-toolbar" role="toolbar"><ul class="wm-toolbar" role="toolbar" aria-label="Wiki"><li id="ca-nstab-main" class="selected"><a href="/HackingWesnoth" role="button" title="View the content page [c]" accesskey="c"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">Page</span></a></li><li id="ca-talk" class="new"><a href="/index.php?title=Talk:HackingWesnoth&action=edit&redlink=1" rel="discussion" role="button" title="Discussion about the content page (page does not exist) [t]" accesskey="t"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">Discussion</span></a></li><li id="ca-history"><a href="/index.php?title=HackingWesnoth&action=history" role="button" title="Past revisions of this page [h]" accesskey="h"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">History</span></a></li><li id="wm-places-menu" class="wm-dropdown"><a class="wm-dropdown-trigger" href="#" title="Places" role="button"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">Places</span><i class="wm-toolbar-dropdown-marker" aria-hidden="true"></i></a><ul class="wm-dropdown-menu" role="menu"><li id="n-mainpage-description"><a href="/Main_Page" role="menuitem" title="Visit the main page [z]" accesskey="z"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Main page</span></a></li><li id="n-recentchanges"><a href="/Special:RecentChanges" role="menuitem" title="A list of recent changes in the wiki [r]" accesskey="r"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Recent changes</span></a></li><li id="n-randompage"><a href="/Special:Random" role="menuitem" title="Load a random page [x]" accesskey="x"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Random page</span></a></li><li id="n-help-mediawiki"><a href="https://www.mediawiki.org/wiki/Special:MyLanguage/Help:Contents" role="menuitem"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Help about MediaWiki</span></a></li></ul><li id="wm-advanced-menu" class="wm-dropdown"><a class="wm-dropdown-trigger" href="#" title="Advanced" role="button"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">Advanced</span><i class="wm-toolbar-dropdown-marker" aria-hidden="true"></i></a><ul class="wm-dropdown-menu" role="menu"><li id="ca-viewsource"><a href="/index.php?title=HackingWesnoth&action=edit" role="menuitem" title="This page is protected. You can view its source [e]" accesskey="e"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>View source</span></a></li><li id="t-whatlinkshere"><a href="/Special:WhatLinksHere/HackingWesnoth" role="menuitem" title="A list of all wiki pages that link here [j]" accesskey="j"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>What links here</span></a></li><li id="t-recentchangeslinked"><a href="/Special:RecentChangesLinked/HackingWesnoth" rel="nofollow" role="menuitem" title="Recent changes in pages linked from this page [k]" accesskey="k"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Related changes</span></a></li><li id="t-specialpages"><a href="/Special:SpecialPages" role="menuitem" title="A list of all special pages [q]" accesskey="q"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Special pages</span></a></li><li id="t-permalink"><a href="/index.php?title=HackingWesnoth&oldid=50375" role="menuitem" title="Permanent link to this revision of the page"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Permanent link</span></a></li><li id="t-info"><a href="/index.php?title=HackingWesnoth&action=info" role="menuitem" title="More information about this page"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Page information</span></a></li></ul></ul><ul class="wm-toolbar" role="toolbar" aria-label="User"><li id="wm-account-menu" class="wm-dropdown"><a class="wm-dropdown-trigger" href="#" title="Your account" role="button"><i class="wm-toolbar-icon" aria-hidden="true"></i><span class="sr-label">Not logged in</span><i class="wm-toolbar-dropdown-marker" aria-hidden="true"></i></a><ul class="wm-dropdown-menu" role="menu"><li id="pt-login"><a href="/index.php?title=Special:UserLogin&returnto=HackingWesnoth" role="menuitem" title="You are encouraged to log in; however, it is not mandatory [o]" accesskey="o"><i class="wm-toolbar-icon" aria-hidden="true"></i><span>Log in</span></a></li></ul></ul></div> <!-- wm-wiki-toolbar --> <h1 class="firstHeading" lang="en">HackingWesnoth</h1> <div id="bodyContent"> <div id="siteSub">From The Battle for Wesnoth Wiki</div> <div id="contentSub"></div> <!-- start wikipage --> <div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><div class="mw-parser-output"><p>This page is designed to be a guide for aspiring Wesnoth programmers on what they need to do to be able to productively contribute to the Wesnoth code base. </p><p>Wesnoth is written in C++, a large and complicated language. There are many C++ programmers, but they tend to have widely varying levels of skills and styles. This page is designed to be a guide as to the skillset needed to contribute to Wesnoth. </p> <div id="toc" class="toc"><div class="toctitle" lang="en" dir="ltr"><h2>Contents</h2></div> <ul> <li class="toclevel-1 tocsection-1"><a href="#C.2B.2B_Quiz"><span class="tocnumber">1</span> <span class="toctext">C++ Quiz</span></a></li> <li class="toclevel-1 tocsection-2"><a href="#Wesnoth_Coding_Style"><span class="tocnumber">2</span> <span class="toctext">Wesnoth Coding Style</span></a> <ul> <li class="toclevel-2 tocsection-3"><a href="#Guideline_1:_Don.27t_prematurely_optimize"><span class="tocnumber">2.1</span> <span class="toctext">Guideline 1: Don't prematurely optimize</span></a></li> <li class="toclevel-2 tocsection-4"><a href="#Guideline_2:_Know_the_Standard_containers_and_use_them"><span class="tocnumber">2.2</span> <span class="toctext">Guideline 2: Know the Standard containers and use them</span></a></li> <li class="toclevel-2 tocsection-5"><a href="#Guideline_3:_Use_the_resource_acquisition_is_initialization_.28RAII.29_idiom"><span class="tocnumber">2.3</span> <span class="toctext">Guideline 3: Use the resource acquisition is initialization (RAII) idiom</span></a></li> <li class="toclevel-2 tocsection-6"><a href="#Guideline_4:_Lean_on_the_compiler_as_heavily_as_you_can"><span class="tocnumber">2.4</span> <span class="toctext">Guideline 4: Lean on the compiler as heavily as you can</span></a></li> </ul> </li> <li class="toclevel-1 tocsection-7"><a href="#See_also"><span class="tocnumber">3</span> <span class="toctext">See also</span></a></li> </ul> </div> <h2><span id="C++_Quiz"></span><span class="mw-headline" id="C.2B.2B_Quiz">C++ Quiz</span></h2> <p>Below is a short C++ quiz that assesses your skills in areas of C++ that are used a lot in Wesnoth. If you know all the answers to the questions, you are probably ready to start working on the Wesnoth code base. If you know most of the answers to the questions, you can probably work on the Wesnoth code base with some oversight from the senior developers. There are good C++ guides for both knowledgeable programmers (such as <a rel="nofollow" class="external text" href="http://www.icce.rug.nl/documents/cplusplus/">The C++ Annotations</a>) and beginners (such as one of the books <a rel="nofollow" class="external text" href="http://stackoverflow.com/q/388242/559931">suggested here</a>). </p> <ol><li>What is a virtual destructor? Why is it needed?</li> <li>What does the class template <tt>shared_ptr</tt> do? What is its purpose?</li> <li>What is a vector, and why would you use it?</li> <li>What is a map, and why would you use it?</li> <li>What are the differences between a reference and a pointer? When should each be used?</li> <li>What is an iterator, and when is it used?</li> <li>What are the memory areas in a C++ program, and what is the purpose of each?</li> <li>When should a member function be <tt>const</tt>? What effect does this have?</li> <li>What is a copy constructor, and what is an assignment operator? When must you define them in a class?</li></ol> <h2><span class="mw-headline" id="Wesnoth_Coding_Style">Wesnoth Coding Style</span></h2> <h3><span id="Guideline_1:_Don't_prematurely_optimize"></span><span class="mw-headline" id="Guideline_1:_Don.27t_prematurely_optimize">Guideline 1: Don't prematurely optimize</span></h3> <blockquote><p>When I was a new and inexperienced coder, I read the following rather famous saying: "Premature optimization is the root of all evil." -- Donald Knuth.</p></blockquote> <p>While I wouldn't then -- and would be hesitant to now -- dispute the opinion of Donald Knuth on any programming topic, this absolute statement confused me. Premature optimization certainly doesn't sound like a wise thing to do, but it sounds somewhat obscure to be the root of all problems in programming. Had Knuth written this phrase after spending too long correcting problems caused by a programmer who was hell-bent on optimization at every turn? </p><p>Now I realize that Knuth was correct. Time and time again programming problems spring from developers making their code too complicated because they are trying to optimize unnecessarily. </p><p>By the <a rel="nofollow" class="external text" href="http://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a> we know that a minority of the code will occupy a majority of the running time. That is, perhaps 90% of the running time of the program will be spend executing just 5% of the code. It is thus generally unnecessary to apply many optimizations at all to most of the program. One can just write the code in a way that is the most readable and maintainable and forget about optimization altogether most of the time. </p><p>Remember also, C++ compilers are good, and smart, and they can execute code fast. Most code will run fast enough, unless you go out of your way to make it run slowly. </p><p>So, the first rule of Wesnoth programming is that unless you have a very good reason to think you need to optimize, do whatever is simplest and most maintainable. </p><p>Many programmers seem to have an obsession with using the control C++ gives them to do all sorts of crazy things. Like make their own memory management routines, or write their own containers, and so forth. Simply, don't. It's possible to write good C++ code very fast using the standard components supplied as part of the language. </p><p>This leads us to our next topic... </p> <h3><span class="mw-headline" id="Guideline_2:_Know_the_Standard_containers_and_use_them">Guideline 2: Know the Standard containers and use them</span></h3> <p>One of the best things about C++ is that the standard supplies some great containers. Always prefer to use them first to store data. That is, </p> <ul><li>prefer to use std::vector to store dynamic arrays</li> <li>prefer to use std::string to store strings (we also provide t_string for a translatable string -- it's based on std::basic_string, which std::string is also based on)</li> <li>prefer to use std::map to store key/value pairs</li> <li>prefer to use std::set to store sets of items (roughly equivalent to the mathematical concept of a set).</li></ul> <p>There are other C++ containers, and you should know about all of them. A good source of documentation on the portion of the C++ standard library known as the Standard Template Library (STL) which contains the standard containers can be found <a rel="nofollow" class="external text" href="http://www.sgi.com/tech/stl/">here</a>. </p><p>By using the standard containers, you should almost never have to manually allocate and delete memory yourself by hand. The containers will automatically allocate and deallocate memory for you. This leads us to our next guideline... </p> <h3><span id="Guideline_3:_Use_the_resource_acquisition_is_initialization_(RAII)_idiom"></span><span class="mw-headline" id="Guideline_3:_Use_the_resource_acquisition_is_initialization_.28RAII.29_idiom">Guideline 3: Use the resource acquisition is initialization (RAII) idiom</span></h3> <p>In C, you might write some code like this: </p> <pre>void myfunction() { char* mystring = (char*)malloc(n); /*some code, which manipulates mystring*/ ... free(mystring); } </pre> <p>This code works, but is error prone. What if the code in the middle exited using a return statement, or a longjmp statement, or in C++, threw an exception? The memory allocated would never be cleaned up, and we would have a memory leak. </p><p>Sure, you're a good programmer, and you probably make sure you're very careful about freeing the string. But what about when this function grows to be 100 lines long (and functions have a way of doing that), and then another programmer who isn't that familiar with the function is trying to fix a critical bug as quickly as they can, that requires adding an early return statement to this function? What about when someone is trying to read the code to scan for memory leaks? Once they see the malloc at the top, they will have to carefully read the entire function, to make sure it's all okay. </p><p>Now if we had this C++ version instead, </p> <pre>void myfunction() { std::string mystring(n,'x'); /*some code, which manipulates mystring*/ } //mystring is destroyed and memory automatically released </pre> <p>None of these problems can possibly happen. mystring will <i>always</i> be released at the end of the function. </p><p>So, this just re-iterates how important C++ containers are, right? Well, yes, but it also shows us that we should always avoid code written like this: </p> <pre>void myfunction() { ...allocate resources... ...use resources ...release resources... } </pre> <p>If you have code like this, you should put the resources in a class that will manage them and release them at the end of the function. If there is no class like that, then you should write one. This goes for all resources: memory, files, threads, and so forth. </p><p>It might sound like a silly mistake that we're protecting against here, one that an experienced programmer wouldn't make. However, almost all programming bugs are due to 'silly mistakes'. This leads us to our next item... </p> <h3><span class="mw-headline" id="Guideline_4:_Lean_on_the_compiler_as_heavily_as_you_can">Guideline 4: Lean on the compiler as heavily as you can</span></h3> <p>Humans make mistakes. Even very stupid mistakes. Computers are as dumb as toast, but they are at least very very consistent. </p><p>For Wesnoth, we try to write code that will make the compiler guard against mistakes as much as possible. The use of RAII as described above is one example of this: writing the code so the compiler and language rules will guarantee it's correct. </p><p>There are some more ways to do this. One big way is to make all code const correct. That is, always define something as 'const' when it shouldn't change its value. If you have a pointer that is meant to be read only, define it as a const pointer. Then if the code is later changed so that your pointer changes the value, the compiler will produce an error. </p><p>Another way is to avoid implicit conversions between objects, and always use the C++-style casts. </p><p><br /> </p> <h2><span class="mw-headline" id="See_also">See also</span></h2> <ul><li><a href="/CodingStandards" title="CodingStandards">CodingStandards</a></li> <li><a href="/PatchSubmissionGuidelines" title="PatchSubmissionGuidelines">PatchSubmissionGuidelines</a></li></ul> <!-- NewPP limit report Cached time: 20241203082305 Cache expiry: 86400 Dynamic content: false CPU time usage: 0.007 seconds Real time usage: 0.008 seconds Preprocessor visited node count: 54/1000000 Preprocessor generated node count: 92/1000000 Post‐expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Highest expansion depth: 2/40 Expensive parser function count: 0/100 Unstrip recursion depth: 0/20 Unstrip post‐expand size: 430/5000000 bytes --> <!-- Transclusion expansion time report (%,ms,calls,template) 100.00% 0.000 1 -total --> </div> <!-- Saved in parser cache with key wiki-mw_:pcache:idhash:1685-0!canonical and timestamp 20241203082305 and revision id 50375 --> </div> <!-- end wikipage --> <div class="printfooter"> Retrieved from "<a dir="ltr" href="https://wiki.wesnoth.org/index.php?title=HackingWesnoth&oldid=50375">https://wiki.wesnoth.org/index.php?title=HackingWesnoth&oldid=50375</a>" </div> <div id="catlinks" class="catlinks" data-mw="interface"><div id="mw-normal-catlinks" class="mw-normal-catlinks"><a href="/Special:Categories" title="Special:Categories">Category</a>: <ul><li><a href="/Category:Development" title="Category:Development">Development</a></li></ul></div></div><div id="lastmod"> This page was last edited on 22 April 2013, at 13:01.</div> <div class="visualClear"></div> </div> <!-- bodyContent --> </div> <!-- end content --> </div> <!-- end main --> <div id="footer-sep"></div> <div id="footer"><div id="footer-content"><div> <a href="https://wiki.wesnoth.org/StartingPoints">Site Map</a> • <a href="https://status.wesnoth.org/">Site Status</a><br /> Copyright © 2003–2024 by <a rel="author" href="https://wiki.wesnoth.org/Project">The Battle for Wesnoth Project</a> — Powered by <a href="https://www.mediawiki.org/">MediaWiki</a><br /> Site design Copyright © 2017–2024 by Iris Morelle </div></div></div> <script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.007","walltime":"0.008","ppvisitednodes":{"value":54,"limit":1000000},"ppgeneratednodes":{"value":92,"limit":1000000},"postexpandincludesize":{"value":0,"limit":2097152},"templateargumentsize":{"value":0,"limit":2097152},"expansiondepth":{"value":2,"limit":40},"expensivefunctioncount":{"value":0,"limit":100},"unstrip-depth":{"value":0,"limit":20},"unstrip-size":{"value":430,"limit":5000000},"timingprofile":["100.00% 0.000 1 -total"]},"cachereport":{"timestamp":"20241203082305","ttl":86400,"transientcontent":false}}});});</script><script>(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":20});});</script></body></html>