{"id":2398,"date":"2020-02-12T21:47:14","date_gmt":"2020-02-12T21:47:14","guid":{"rendered":"http:\/\/www.andygibson.net\/blog\/?p=2398"},"modified":"2020-02-11T11:55:04","modified_gmt":"2020-02-11T11:55:04","slug":"from-java-to-c-project-setup","status":"publish","type":"post","link":"https:\/\/www.andygibson.net\/blog\/programming\/from-java-to-c-project-setup\/","title":{"rendered":"Simple C++ Project Setup With CMake"},"content":{"rendered":"\n<p>As a Java developer, I wanted  to dabble with a C++ project, something I&#8217;ve not done for a while. I was looking into how to structure my project with a view to getting started quickly, but ensuring that if I wanted to expand the project, I wouldn&#8217;t have to restructure it in order to keep things organised. This post talks about that project and the <a href=\"https:\/\/github.com\/andygibson\/blog-post-code\/tree\/master\/c\/cmake-basic\">source is available<\/a> from my blog post code repository.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Coming from a Java background, we are pretty lucky that Java has had multiple build tools that can help manage Java projects such as organising class and test sources, handling dependencies, running tests and so on. It was not always this way, originally, there were IDE specific builders that put the source in their own structures and knew how to build them. This was problematic if you wanted to build outside of the IDE, and wouldn&#8217;t work in today&#8217;s world of continuous integration.  Ant came along and let us write build scripts that could take source code of any structure and produce class, source and javadoc jar files for them, and IDEs could take advantage of such scripts.<\/p>\n\n\n\n<p>With Maven, and later Gradle, we were able to create projects with a predefined structure that could be compiled easily just adding a class or test class file in a specific directory. IDEs were able to provide plugins to support these frameworks creating a fairly rich environment where it is easy to get started with Java.<\/p>\n\n\n\n<p>With C++ (and of course plain old C), we don&#8217;t have the same solutions, historically, tools like Make have provided Ant-like build systems where you can put your source code where you like and write a script to find and build it. C++ has many more options with regards to compilation for things like build types (Release, Debug etc), linking dynamic &amp; static libs and the target platform to name a few. Some of this complexity was been wrapped up in a tool called CMake which is a higher level abstraction of the build process. Technically, its not a build system, it creates a configuration from which the project can be built.<\/p>\n\n\n\n<p>So I wanted to come up with a basic template for a C++ project that can be built with CMake, and used as the basis for other projects. I wanted to be able to compile and run from the command line and also be able to run from an IDE such as Eclipse and\/or KDevelop. I also wanted it to be structured such that it wasn&#8217;t overly verbose for small projects but flexible enough that I can expand it later on and refactor as needed. Longer term I want to add testing in, but we&#8217;ll start without for now.<\/p>\n\n\n\n<p>I went for a container project which contains sub projects for the main application, and a static linked library. The library could always be spun out as a dynamic library and moved into its own project. <\/p>\n\n\n\n<h2>Sample Project<\/h2>\n\n\n\n<p>Our project will have the following directory structure:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; gutter: false; title: ; notranslate\" title=\"\">\nSample Project\n     |\n     | -- calcApp\n     |\n     | -- calcLib\n<\/pre><\/div>\n\n\n<p>CMake works by having <code>CMakeLists.txt<\/code> files in each folder of the project and sub projects. In the top level folder we put a <code>CMakeLists.txt<\/code> file that is for the project, and it includes the two subdirectories below it. CMake will drill down, find the <code>CMakeLists.txt<\/code> file in the subdirectories and build elements in those folders.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncmake_minimum_required(VERSION 3.5)\n\nproject(someProject)\n\nadd_subdirectory(calcLib)\nadd_subdirectory(calcApp)\n<\/pre><\/div>\n\n\n<p>The first line defines the <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/cmake_minimum_required.html\" target=\"_blank\">minimum version<\/a> of CMake required to build this project. The <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/project.html\" target=\"_blank\">project<\/a>() definition defines the project name. We then add the two <a href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/add_subdirectory.html\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">subdirectories<\/a> for our sub-projects.<\/p>\n\n\n\n<h3>calcLib<\/h3>\n\n\n\n<p>Our next step is to implement the <code>calcLib<\/code> and set up the CMake files for it. We will have a simple <code>Calc<\/code> class that just has a couple of methods.<\/p>\n\n\n\n<p>C++ often has header files and source files separately, the header defines the interface to a method or class while the source implements it. Our header will go in the include directory of the lib, and goes in a subdirectory so we can make include file names more unique. The following is the content of <code>calcLib\/include\/calc<\/code>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#ifndef CALCLIB_INCLUDE_CALC_CALC_H_\n#define CALCLIB_INCLUDE_CALC_CALC_H_\n\nclass Calc {\npublic:\n\tint add(int a,int b);\n\tint sub(int a,int b);\n};\n\n#endif \/* CALCLIB_INCLUDE_CALC_CALC_H_ *\/\n<\/pre><\/div>\n\n\n<p>We can create an implementation of this in the <code>calcLib\/src\/Calc.cpp<\/code> file:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &quot;calc\/Calc.h&quot;\n\nint Calc::add(int a, int b) {\n\treturn a+b;\n}\n\nint Calc::sub(int a, int b) {\n\treturn a-b;\n}\n<\/pre><\/div>\n\n\n<p>We include our header file, and then proceed to complete the implementations of the interface defined in the header file. Note that we prefix our header file with <code>calc<\/code> from the <code>calc<\/code> subdirectory in our include directory.<\/p>\n\n\n\n<p>Our last piece for the lib is the <code>calcLib\/CMakeLists.txt<\/code>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nadd_library(calcLib src\/Calc.cpp)\n\nmessage(&quot;CalcLib current source dir = ${CMAKE_CURRENT_SOURCE_DIR}&quot;)\n\ntarget_include_directories( calcLib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}\/include)\n<\/pre><\/div>\n\n\n<p>Since C++ lets us build executables or libraries we need to tell CMake what we want our target to be. <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/add_library.html\" target=\"_blank\">add_library<\/a> is used to define a library target, give it a name, and define the source files for it. In this case, we are creating a library called <code>calcLib<\/code> and adding our <code>src\/Calc.cpp<\/code> source file. <\/p>\n\n\n\n<p>The <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/message.html\" target=\"_blank\">message<\/a> command is used to log messages back to the user. CMake internal or user defined variables can be used inside the string to log them as part of the message.  This isn&#8217;t needed, I just included to show you how to create output.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/target_include_directories.html\" target=\"_blank\">target_include_directories<\/a> is used to define the include directory for this lib. Note that we use the target name <code>calcLib<\/code> to attach the include directory to the target. Because of the nature of C++ with regards to libraries and linking there are a few options on this command to define the visibility of the includes. We have defined ours as PUBLIC for now.<\/p>\n\n\n\n<h3>calcApp<\/h3>\n\n\n\n<p>Now we have our library all completed, we can work on our main app in the calcApp directory. This is a simple <code>main.cpp<\/code> class which prints a message and invokes our calculator to show it is all hooked up. <\/p>\n\n\n\n<p><code>calcApp\/main.cpp<\/code>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;iostream&gt;\n#include &quot;calc\/Calc.h&quot;\n\nint main() {\n\tCalc calc;\n\tstd::cout &lt;&lt; &quot;Hello World 12+7 = &quot; &lt;&lt; calc.add(12,7) &lt;&lt; &quot;\\n&quot;;\n}\n<\/pre><\/div>\n\n\n<p>Pretty simple stuff. We need to also add a CMakeLists.txt file which will define the executable and pull in our library. <\/p>\n\n\n\n<p><code>calcApp\/CMakeLists.txt<\/code> <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nadd_executable(calcApp main.cpp)\n\ntarget_link_libraries(calcApp calcLib)\n<\/pre><\/div>\n\n\n<p><a rel=\"noreferrer noopener\" aria-label=\"add_executable (opens in a new tab)\" href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/add_executable.html\" target=\"_blank\">add_executable<\/a> is like add_library, it lets us define an executable we want to create, gives it a target name and lets us specify the source files to be added to it.<\/p>\n\n\n\n<p><a href=\"https:\/\/cmake.org\/cmake\/help\/latest\/command\/target_link_libraries.html\">target_link_libraries<\/a> lets us link our library into the executable when it gets built. In this case we are doing a static link and the library will be pulled into the executable.<\/p>\n\n\n\n<h3>Building It All<\/h3>\n\n\n\n<p>That should be everything, and we should be able to build and run our app. You can build the project by opening a command line, going to the project root folder and typing: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmkdir build\ncd build\ncmake ..\nmake\n<\/pre><\/div>\n\n\n<p>That should build the project for you, and you can run the executable from <code>calcApp\/calApp<\/code><\/p>\n\n\n\n<p>That about wraps it up, you can get the source code from my blog post code git repository under <a href=\"https:\/\/github.com\/andygibson\/blog-post-code\/tree\/master\/c\/cmake-basic\">cmake-basic<\/a>. <\/p>\n\n\n\n<p>There are a lot of knobs to play with with regards to building C++ projects, and how they are structured. With Java, while we have the option of adding jars to executables at runtime through the class path, its often the case that we just build a jar containing all the code we need. Similarly, we could bind java libraries at run time, but often choose not to. With C++ here we have a basic outline of a project that should cover simple cases. <\/p>\n\n\n\n<p>Next I&#8217;m going to be looking at incorporating a test framework to give us a real base project to work with.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>As a Java developer, I wanted to dabble with a C++ project, something I&#8217;ve not done for a while. I was looking into how to structure my project with a view to getting started quickly, but ensuring that if I wanted to expand the project, I wouldn&#8217;t have to restructure it in order to keep [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[80],"tags":[132,131,6],"_links":{"self":[{"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/posts\/2398"}],"collection":[{"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/comments?post=2398"}],"version-history":[{"count":12,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/posts\/2398\/revisions"}],"predecessor-version":[{"id":2412,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/posts\/2398\/revisions\/2412"}],"wp:attachment":[{"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/media?parent=2398"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/categories?post=2398"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.andygibson.net\/blog\/wp-json\/wp\/v2\/tags?post=2398"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}