<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Iván Mejía on Medium]]></title>
        <description><![CDATA[Stories by Iván Mejía on Medium]]></description>
        <link>https://medium.com/@ivan.mejia?source=rss-b2186fbe4ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ym39gwx33cQdb7qei_IC5Q.jpeg</url>
            <title>Stories by Iván Mejía on Medium</title>
            <link>https://medium.com/@ivan.mejia?source=rss-b2186fbe4ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:04:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivan.mejia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Modern C++ micro-serivce + REST API, Part II]]></title>
            <link>https://medium.com/@ivan.mejia/modern-c-micro-serivce-rest-api-part-ii-7be067440ca8?source=rss-b2186fbe4ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be067440ca8</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Iván Mejía]]></dc:creator>
            <pubDate>Tue, 31 Jan 2017 00:29:17 GMT</pubDate>
            <atom:updated>2017-03-30T14:33:32.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaHQFvaYyQoYez2yQQfKNA.png" /></figure><p>This is the second part of my previous story: <a href="https://medium.com/audelabs/modern-c-micro-service-implementation-rest-api-b499ffeaf898">Modern C++ micro-service implementation + REST API</a> where I basically discuss the simplicity you can achive when implementing a micro-service using Modern C++, simplicity that challenges node.js’s with the extra benefit of great performance at no expense in productivity, so if you haven’t read it and you are interested on C++ micro-serivces on your next backend implementation you might want to read that story first.</p><p>In this occasion we’ll talk about asynchronous request processing and how to handle a request using pplx::task. There are a lot already covered about pplx::task, wrote by very <a href="https://www.codeproject.com/articles/585998/csharp-style-async-await-in-cpl">competent folks</a> so the idea here is to show you how to use it in the context of our C++ micro service, to implement REST APIs and a bit of more detail about how <a href="https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)">asynchrony</a> can help to implement a lock-free micro service that achieves great performance and again simplicity in code, thanks to the elegant pplx library.</p><h4>Tasks</h4><p>The pplx::task class follows the approach of chaining tasks together, each task holds its own state and they progress to the next task via <em>continuations</em>. This chaining concept helps mantain in mind that a task maps into a single transaction allowing a cleaner implementation and due to the tasks hold its own state avoids excessive locking. Tasks implement the <a href="https://en.wikipedia.org/wiki/Futures_and_promises">promise pattern</a> which helps to avoid too much levels of chaining that can lead to poor code readability and reduces latency. Another option expecially for more complex cases could be the use of Fibers or Coroutines, but that is out of the scope of this article.</p><h4>Modifying Modern C++ micro service</h4><p>First of all we need to create some infrastructure so let’s say we want to create a user sign-up/sign-on service, so before we continue please git clonethe <a href="https://github.com/ivanmejiarocha/micro-service">sample code found here</a> and build it following the instructions in the README.mdfile.</p><p>Then please come back here and cd micro-service/source and add the files: user_manager.hppand user_manager.cpp using your favorite editor.</p><blockquote>I am using Visual Studio Code (VSC for short) and you can<a href="https://medium.com/audelabs/c-development-using-visual-studio-code-cmake-and-lldb-d0f13d38c563"> follow here some instructions</a> to use it for this article too, but you can use vim, emacs, Xcode, Visual Studio, etc.</blockquote><p>please edit the file micro-service/CMakeLists.txt adding the user_manager.cpp to the list of sources as follows (add the line in <strong>bold)</strong>:</p><pre>add_executable(${PROJECT_NAME} ./source/main.cpp<br>                               ./source/microsvc_controller.cpp<br>                               <strong>./source/user_manager.cpp</strong><br>                               ./source/foundation/network_utils.cpp<br>                               ./source/foundation/basic_controller.cpp)</pre><p>Now we are not going to use any full fledge database, but an in memory database so let’s go through the following code, feel free to copy and paste it into the file user_manager.hpp you just created:</p><pre>#pragma once</pre><pre>#include &lt;map&gt;<br>#include &lt;std_micro_service.hpp&gt;</pre><pre>typedef struct {<br>   std::string email;<br>   std::string password;<br>   std::string name;<br>   std::string lastName;   <br>} UserInformation;</pre><pre>class UserManagerException : public std::exception {<br>   std::string _message;<br>public:<br>   UserManagerException(const std::string &amp; message) : <br>                         _message(message) { }<br>   const char * what() const throw() {<br>      return _message.c_str();<br>   }<br>};</pre><pre>// alias declaration of our In Memory database...<br>using UserDatabase = std::map&lt;std::string, UserInformation&gt;;</pre><pre>class UserManager {<br>public:</pre><pre>   void signUp(const UserInformation &amp; userInfo)  <br>        throw(UserManagerException);</pre><pre>   bool signOn(const std::string email, <br>               const std::string password, <br>               UserInformation &amp; userInfo);<br>};</pre><p>Our <strong>user manager</strong> micro service will manage the users registration and authentication, so as shown above we are declaring our UserManager class and at the top we declare the type UserInformation, that represents one record in our In Memory database, then we declare UserManagerException derived from std::exception that we’ll use to inform the controller (find declaration in source/microsvc_controller.hpp file) about any problem occurred on aUserManger object. In the middle we declare an alias of std::map&lt;std::string, UserInformation&gt; using the name UserDatabase that will represent the In Memory database, meaning it’s never persisted to a file, it goes away when the micro service shuts down, but it serves to our sample purposes, I leave it to you the code to incorporate MongoDB, Postgres or whatever is your favorite database.</p><p>Finally is the declaration of UserManager class, which basically has two methods:</p><ul><li><strong>signUp</strong>, to register users</li><li><strong>signOn</strong>, to authenticate users</li></ul><p>Now lets see the implementation which you can as well copy/paste to the file user_manager.cpp you have already created:</p><pre>#include &lt;mutex&gt;<br>#include &quot;user_manager.hpp&quot;</pre><pre>UserDatabase usersDB;<br>std::mutex usersDBMutex;</pre><pre>void UserManager::signUp(const UserInformation &amp; userInfo) throw(UserManagerException) {<br>   <br>   std::unique_lock&lt;std::mutex&gt; lock { usersDBMutex };</pre><pre>   if (usersDB.find(userInfo.email) != usersDB.end()) {<br>      throw UserManagerException(&quot;user already exists!&quot;);<br>   }</pre><pre>   usersDB.insert(<br>      std::pair&lt;std::string, UserInformation&gt;(userInfo.email, <br>                                              userInfo));   <br>}</pre><pre>bool UserManager::signOn(const std::string email, <br>                         const std::string password, <br>                         UserInformation &amp; userInfo) {   <br>   if (usersDB.find(email) != usersDB.end()) {<br>      auto ui = usersDB[email];<br>      if (ui.password == password) {<br>         userInfo = ui;<br>         return true;<br>      }         <br>   }<br>   return false;<br>}</pre><p>First at the top you can see the declaration of a global variable of type UserDatabase named usersDB and a global variable of typestd::mutex named usersDBMutex which acts as a lock mechanism to avoid that multiple threads falling into a race condition mess up our users database under heavy concurrency.</p><blockquote>Our lock mechanism is a very simple implementation of what a comercial database provide out of the box to access the data under heavy concurrency, we use it only for sample purposes and to handle the concurrency on our In Memory database.</blockquote><p>The signUp method declares a variable of type std::unique_lock named lock that aquires a lock on our global mutex usersDBMutex. (if possible, otherwise it blocks), this will prevent other threads to corrupt our database. Then under the lock blanket signUp validates the user’s email doesn’t exists otherwise throws an UserManagerException indicating the user already exists. If everything goes fine it inserts the user on the database and leaves but before executes the lock’s destructor which releases the mutex whether there was an exception or not.</p><p>The signOn method simply validates the email and password provided by the user and returns true if found otherwise false which means the authentication failed.</p><h4>Implementing REST API using a sync tasks</h4><p>Let’s say we are going to implement the following two REST APIs:</p><ul><li><strong>users/signup</strong>, registers a user with our UserManager micro service and it accepts a JSON body with the following format:</li></ul><pre>{ <br>    &quot;email&quot;:&quot;<a href="/service/mailto:ivan@ivmero.com">ivan@email.com</a>&quot;,<br>    &quot;password&quot;:&quot;allmighty&quot;,<br>    &quot;name&quot;:&quot;ivan&quot;,<br>    &quot;lastName&quot;:&quot;mejia&quot;<br>}</pre><ul><li><strong>users/signon</strong>, authenticates a user using our core service implementationUserManager which following the specification of <a href="https://en.wikipedia.org/wiki/Basic_access_authentication">HTTP Basic Authentication</a> will require the credentials passed encoded in base64 format, so the user and password are not passed on the URL but on the Authorization HTTP header and not in this case but can be protected using SSL, which BTW is supported by C++ REST SDK as well and I’ll cover it in a future article.</li></ul><p>Ok now that we have our core service implementation under UserManager, is time to process the requests using the asynchronous power of pplx::task, let’s implement out REST APIs</p><h4>Implementing “users/singup” API</h4><p>Let’s say UserManager::signUp is a long running operation where we need to deffer the execution to a separate thread while letting the calling thread go back to the pool to serve more requests. so please open the file microsvc_controller.cpp and let’s implement the handlePost method which currently looks like this:</p><pre>void MicroserviceController::handlePost(http_request message) {</pre><pre>    message.reply(status_codes::NotImplemented,    <br>                  responseNotImpl(methods::POST));</pre><pre>}</pre><p>remove all the content and copy/paste inside the following code so MicroserviceController::hadlePost looks like this:</p><pre>#include &lt;std_micro_service.hpp&gt;<br>#include &quot;microsvc_controller.hpp&quot;</pre><pre><strong>#include &quot;user_manager.hpp&quot;</strong></pre><pre><strong>...</strong></pre><pre>void MicroserviceController::handlePost(http_request <strong>message</strong>) {<br>    auto path = <strong>requestPath</strong>(message);<br>    if (!path.empty() &amp;&amp; <br>         path[0] == <strong>&quot;users&quot;</strong> &amp;&amp; <br>         path[1] == <strong>&quot;signup&quot;</strong>) {<br>        message.<br>        extract_json().<br>        then([=](json::value request) {<br>            try {<br>                UserInformation userInfo { <br>                    request.at(&quot;email&quot;).as_string(),<br>                    request.at(&quot;password&quot;).as_string(),<br>                    request.at(&quot;name&quot;).as_string(),<br>                    request.at(&quot;lastName&quot;).as_string()<br>                };</pre><pre>                UserManager users;<br>                users.signUp(userInfo);</pre><pre>                json::value response;<br>                response[&quot;message&quot;] = json::value::string(<br>                                        &quot;succesful registration!&quot;);<br>                message.reply(status_codes::OK, response);<br>            }<br>            catch(UserManagerException &amp; e) {<br>                message.reply(status_codes::BadRequest, e.what());<br>            }<br>            catch(json::json_exception &amp; e) {<br>                message.reply(status_codes::BadRequest);<br>            }<br>        });<br>    }<br>}</pre><p>The code above implements the handler for our <em>users/signup</em> API so let’s go through the code, first we parse the request’s URL, you can find the implementation of requestPath on the file sources/foundation/basic_controller.cpp which returns an std::vector&lt;std::string&gt; containing each part of the path.</p><p>Then we validate the path variable is not empty and contains the required sections in the path that matches with the API that we are implementing.</p><p>Finally we use the variable message of type http_request passed as the argument of handlePost, and use the method extract_json that extracts the JSON payload from the request. http_request has this and other handy methods like extract_string, extract_vector, etc. you can check on the <a href="http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html">reference documentation</a>. The method extract_json() returns an pplx::task&lt;json::value&gt; that <strong>executes <em>asynchronously</em> on a thread other than the thread where the request is being served, releasing the serving thread and returning it to the main thread pool so it can serve more requests</strong> <strong>while the json extraction tasks deals with the JSON body sent in the request, letting our micro service to handle a good deal of concurrency.</strong></p><p>At completion of extract_json is called what is know as a <em>value based continuation</em>, a continuation that receives a json::value value argument.</p><pre>message.<br>extract_json(). <strong>// return pplx::task&lt;json::value&gt; </strong><br>then([=](json::value request) { <strong>// value based continuation</strong><br>...<br>}</pre><p>A <em>continuation</em> as you see acts as a callback, executed after task completion, then inside a <em>continuation</em> is possible to perform another task and so on, here is where you most be careful not to impement too much nesting of tasks otherwise you could end with code difficult to read and maintain.</p><p>The code above can be modified into the following form known as a <em>task based continuation</em>:</p><pre>message.<br>   extract_json().<br>   then([=](<strong>pplx::task&lt;json::value&gt;</strong> requestTask) {<br>       <strong>auto</strong> <strong>request = requestTask.get();<br>       ...<br>   </strong>});</pre><p>where the <em>continuation</em> parameter in this case is of type pplx::task&lt;json::value&gt;, where we can call theget() method that returns the result produced by the task if it already finished otherwise will block until the task has finished. More on this ahead.</p><p>Another way to modify the code above is:</p><pre>message.<br>   extract_json().<br>   then([=](<strong>pplx::task&lt;json::value&gt;</strong> requestTask) {<br>       <strong>requestTask.then([=](json::value request) {<br>          ...</strong></pre><pre><strong>       });       <br>   </strong>});</pre><p>on this second option you add an extra level of nesting but a new thread executes and on completion calls the <em>continuation</em>, so you will have three threads instead of two as in the first case when we used the get() method.</p><p>You might wonder why you want to use these two options? well, let’s suppose you have a really big JSON request that might require some time to receive and then parse, then you’ll probably want as well read the JSON asynchronously keeping the micro service responsive.</p><h4>Implementing “users/signon” API</h4><p>This API deals with reading the credentials from the Authorization HTTP header decoding them from base64 to plain text string. So in the request the <em>Authorization</em> header could look like this:</p><pre>Authorization Basic dXNlckBlbWFpbGRvbWFpbi5jb206c2VjcmV0d29yZAo=</pre><p>where credentials are passed in plain text, formatted in the following way:</p><pre>&lt;user email&gt;:&lt;password&gt;</pre><p>you can use the following command on your terminal to generate the base64 sequence as follows:</p><pre>$ echo user@emaildomain.com:secretword | base64<br>dXNlckBlbWFpbGRvbWFpbi5jb206c2VjcmV0d29yZAo=</pre><p>now, please open the file source/microsvc_controller.cpp and on the MicroserviceController::handleGet method which looks like this:</p><pre>void MicroserviceController::handleGet(http_request message) {<br>   auto path = requestPath(message);<br>   if (!path.empty()) {<br>      if (path[0] == &quot;service&quot; &amp;&amp; path[1] == &quot;test&quot;) {<br>         auto response = json::value::object();<br>         response[&quot;version&quot;] = json::value::string(&quot;0.1.1&quot;);<br>         response[&quot;status&quot;] = json::value::string(&quot;ready!&quot;);<br>         message.reply(status_codes::OK, response);<br>      }<br>   }<br>   else {<br>      message.reply(status_codes::NotFound);<br>   }<br>}</pre><p>please add the following code (you can copy/paste the code in <strong>bold</strong>) so Microservice::handleGet look like this now:</p><pre><strong>#include &lt;tuple&gt;<br>...</strong></pre><pre>void MicroserviceController::handleGet(http_request message) {<br>   auto path = requestPath(message);<br>   if (!path.empty()) {<br>      if (path[0] == &quot;service&quot; &amp;&amp; path[1] == &quot;test&quot;) {<br>         ...<br>      }<br><strong>      else if (path[0] == &quot;users&quot; &amp;&amp; path[1] == &quot;signon&quot;) {<br>         pplx::create_task([=]() -&gt; std::tuple&lt;bool, UserInformation&gt; {</strong></pre><pre><strong>            auto headers = message.headers();<br>            if (message.headers().find(&quot;Authorization&quot;) == headers.end()) <br>                throw std::exception();</strong></pre><pre><strong>            auto authHeader = headers[&quot;Authorization&quot;];<br>            auto credsPos = authHeader.find(&quot;Basic&quot;);<br>            if (credsPos == std::string::npos) <br>                throw std::exception();<br>            <br>            auto base64 = authHeader.substr(credsPos + <br>                             std::string(&quot;Basic&quot;).length() + 1);<br>            if (base64.empty()) <br>                throw std::exception();</strong></pre><pre><strong>            auto bytes = utility::conversions::from_base64(base64);<br>            std::string creds(bytes.begin(), bytes.end());<br>            auto colonPos = creds.find(&quot;:&quot;);<br>            if (colonPos == std::string::npos) <br>                throw std::exception();</strong></pre><pre><strong>            auto useremail = creds.substr(0, colonPos);<br>            auto password = creds.substr(colonPos + 1, creds.size()  - colonPos - 1);            <br>                    <br>            UserManager users;<br>            UserInformation userInfo;            <br>            if (users.signOn(useremail, password, userInfo)) {<br>               return std::make_tuple(true, userInfo);<br>            }<br>            else {<br>               return std::make_tuple(false, UserInformation {});<br>            }</strong></pre><pre><strong>        })<br>        .then([=](pplx::task&lt;std::tuple&lt;bool, UserInformation&gt;&gt; resultTsk) {<br>             try {<br>                auto result = resultTsk.get();</strong></pre><pre><strong>                if (std::get&lt;0&gt;(result) == true) {<br>                    json::value response;<br>                    response[&quot;success&quot;] = json::value::string(&quot;welcome &quot; + std::get&lt;1&gt;(result).name + &quot;!&quot;);                    <br>                    message.reply(status_codes::OK, response);<br>                }<br>                else {<br>                    message.reply(status_codes::Unauthorized);<br>                }<br>            }<br>            catch(std::exception) {<br>                message.reply(status_codes::Unauthorized);<br>            }<br>        });<br>   }<br></strong>   else {<br>      message.reply(status_codes::NotFound);<br>   }<br>}</pre><p>In the new code you’ll notice right in next line to the path validation, a call to pplx::create_task this function creates a task which returns the type specified in the lambda; in this case it returns a <a href="https://en.wikipedia.org/wiki/Tuple">tuple</a> containing a bool and UserInformation. That’s why we declare at the top the #include &lt;tuple&gt; statement BTW.</p><p>We have created this task to perform the user’s authentication on a different thread than the one serving the request, so again releasing the serivng thread to the pool and serve more requests, while we perform our heavy operation on a separate thread.</p><p>The remaing code is very simple:</p><ol><li>Reads the HTTP headers provided by http_request on its headers() method, validates the <em>Authorization</em> header exists.</li><li>Read the credentials base64 encoded into the string variable base64 and decode them into a bytes array using utility::conversions::from_base64(...) utility function.</li><li>Extract the <em>user</em> and <em>password</em> and pass them to UserManager::signOn method to authenticate the user which on case of success returns a tuple with a boolean value to indicate authentication’s success or failure and the user information on the variable userInfo.</li></ol><p>Finally in the continuation code we receive the response tuple where if the fist element is <em>true</em> indicates the authetication was successful and we use the UserInformation to send back the response:</p><pre>{<br>  &quot;success&quot;: &quot;welcome ivan!&quot;<br>}</pre><p>otherwise the user won’t be granted access and we’ll send back an Unauthorized error.</p><p>In the code above you will notice that in case of error an std::exception is thrown on task’s main lambda, but they are catched in the <em>continuation.</em> To be able to do that we need to implement a <em>task based continuation</em> and on the task passed resultTsk call the get() method in other to catch any exception.</p><h4>Benchmark</h4><p>In the our micro service <a href="https://github.com/ivanmejiarocha/micro-service">repository</a> you can find a <a href="https://github.com/ivanmejiarocha/micro-service/tree/master/tests/wrk">Lua script</a> that can be executed using the <a href="https://github.com/giltene/wrk2">WRK2 benchmark tool</a> that shows some pretty good results as shown on the README.md of the project. You can create the Lua scripts to test our REST APIs following the ones found under tests/wrk.</p><h4>Conclusion</h4><p>As you can see the asynchronous execution of each request on the server allows us to have a listener thread pool quite responsive due to the lengthily processing can be decoupled from the serving thread releasing it to serve more requests while the lengthily operation can inform of its results on the thread is running.</p><p>Additionally the simplicity of the pplx::task API allows us to create again code that challenges other productive tools with the benefit of astonishing performance, in next article I’ll talk about how to run this micro service inside a Docker container.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be067440ca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern C++ micro-service implementation + REST API]]></title>
            <link>https://medium.com/@ivan.mejia/modern-c-micro-service-implementation-rest-api-b499ffeaf898?source=rss-b2186fbe4ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b499ffeaf898</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Iván Mejía]]></dc:creator>
            <pubDate>Tue, 03 Jan 2017 23:08:25 GMT</pubDate>
            <atom:updated>2018-08-31T16:56:05.856Z</atom:updated>
            <content:encoded><![CDATA[<p>Part II of this article</p><p>Nowdays there is a lot of hype about node.js in the micro-service field due to its productivity and the great community, and indeed node.js is really a powerful platform for cloud computing development, but don’t forget that all its productivity relays on various layers of abstraction which come with a penalty in performance and a huge stack of components to make it work. But I do not want to start here a polemic about which one is best, this article is about using modern C++ to implement a microservice where the idea is using the modern syntax to reach the level of productivity that node.js provides but with the performance benefits of C++, and if you are like me that loves C++ and its great performance thanks to its zero levels of abstractions, then this article is for you.</p><p>To implement the C++ micro-service with the less amount of code we will make use of a great library from Microsoft called the <a href="https://github.com/Microsoft/cpprestsdk">C++ REST SDK</a>, this is a cross-platform library meaning it runs on Linux, macOS and Windows, this library uses modern C++11 syntax and provides all the threading and networking I/O goodies that we require to implement a full-fledge micro-service that exposes a REST API interface.</p><p>To write and debug the code we’ll use Visual Studio Code (VSC), but you can use Xcode on macOS or Visual Studio on Windows, vim, Emacs, etc. whatever you fill confortable with because the project does not depend on any IDE. But if you don’t know how to use VSC but are curious about it check<a href="https://medium.com/audelabs/c-development-using-visual-studio-code-cmake-and-lldb-d0f13d38c563#.naylj89mb"> out my article about it</a>.</p><h4>Pre-requisites</h4><ul><li>I am working on macOS and I use <a href="http://brew.sh/">homebrew</a> to install most of my dependencies so the following command will suffice:</li></ul><pre>$ brew update<br>$ brew install cmake openssl boost </pre><ul><li>After <em>brew install </em>you should see the following directories (be aware that the versions shown are the latests available at the time of this article):</li></ul><pre>/usr/local/Cellar<strong>/boost</strong>/<strong>1.60.0_1</strong><br>/usr/local/Cellar<strong>/cmake</strong>/<strong>3.4.2</strong><br>/usr/local/Cellar<strong>/openssl</strong>/<strong>1.0.2f</strong></pre><h4>Build the sample code</h4><p>Clone the <a href="https://github.com/ivanmejiarocha/micro-service">micro-service repository</a> from github and follow there the instructions to build the sample code, then please come back here for further explanation of the code.</p><h4>About C++ REST SDK</h4><p>This is a cross-plaform open source library from Microsoft that allows you to create asynchronous REST clients on top of the Concurrency Runtime under the namespace <strong>pplx</strong> but it enables you to build REST servers as well. This library is adaptive which means that depending on the operating system you are compiling it, it takes care of the native implementations for example the <strong>http_listener</strong> class is implemented on top of IO Completion Ports (IOCP), which on <strong>macOS</strong> this is accomplished through the <a href="https://en.wikipedia.org/wiki/Kqueue"><strong>kqueue</strong></a><strong> </strong>system call, on Linux this is accomplished through the <a href="https://en.wikipedia.org/wiki/Epoll"><strong>epoll</strong></a> system call and on Windows through <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363862%28v=vs.85%29.aspx"><strong>CreateIoCompletionPort</strong></a><strong> </strong>but you don’t need to know all about those IO APIs due to C++ REST SDK takes care of it becasue it additionally relies heavily on <a href="http://www.boost.org/doc/libs/1_62_0/doc/html/boost_asio.html">boost asio library</a> all throught a single class called <strong>http_listener</strong>, but that is just an example of the adaptiveness of the library, the same applied for threads, sockets, character encoding, etc. elegantly wrapped on modern C++11 classes.</p><p>We are using C++ REST SDK to create a multi-threaded server that exposes a REST API and that can perfectly work as the basis of a full-fledge micro-service, capable to be used on any serious micro-serivce architecture backend implementation, specially on mission critical and high performance micro-services.</p><h4><strong>Micro-serivce implementation</strong></h4><p>The service has the following basic architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5fzrfcweHvdCl-TJu3dCw.png" /></figure><p>where a controller basically provides the handlers for each of the HTTP methods:</p><ul><li>GET</li><li>POST</li><li>PUT</li><li>DELETE</li><li>HEAD</li><li>OPTIONS</li><li>TRACE</li><li>CONNECT</li><li>MERGE</li><li>PATCH</li></ul><p>for more information about each method <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">please take a look here</a>.</p><p>The controller internally makes use of the class <em>web::http::experimental::listener::</em><strong>http_listener</strong> which basically enables the service to listen for HTTP requests.</p><p>Once a request is received the <strong>http_listener</strong> verifies is a valid HTTP request and that the HTTP method is supported by the service, if that is the case then handles the request to the <strong>controller</strong> for further processing in a thread different than the one demultiplexing the original request, this allow you to perform the request’s logic in a separate thread of execution laving the <strong>http_listener</strong> ready to <strong>accept</strong> more request(s).</p><p>In order for the <strong>http_listener</strong> to know which handler to invoke on the <em>Controller </em>you need to register your handlers with the <strong>http_listener</strong>. For that we have the class <em>MicroserviceController </em>which derives from <em>BasicController </em>and <em>Controller</em> where <em>BasicController </em>provides a wrapper around <strong>http_listener<em> </em></strong>and some convenient methods to read the endpoint string and decide if the service should figure out the host’s IP address whether it is IP4 or IP6, or you can pass a fixed domain name or IP address; and the <em>Controller</em><strong> </strong>provides an interface which the concrete <em>Controller </em>in this case <em>MicroserviceController </em>implements for each HTTP method, so open the file <em>microsvc_controller.hpp </em>and you will see the following code:</p><pre>#pragma once</pre><pre>#include &lt;basic_controller.hpp&gt;</pre><pre>using namespace cfx;</pre><pre>class MicroserviceController : public BasicController, Controller {<br>public:<br> MicroserviceController() : BasicController() {}<br> ~MicroserviceController() {}<br> void handleGet(http_request message) override;<br> void handlePut(http_request message) override;<br> void handlePost(http_request message) override;<br> void handlePatch(http_request message) override;<br> void handleDelete(http_request message) override;<br> void <strong>initRestOpHandlers</strong>() override;<br>};</pre><p>you can see in the code above that <em>MicroserviceController</em><strong> </strong>overrides the method <em>BasicController::initRestOpHandlers(),</em> and all the methods from the <em>Controller </em>interface. Now if you open the correspoding *.cpp file you’ll see the code that registers the handlers on the <em>Controller </em>interface with the <strong>http_listener</strong> represented by the member variable <em>_listener</em>:</p><pre>void MicroserviceController::initRestOpHandlers() {<br> _listener.support(methods::GET, <strong>std::bind</strong>(<strong>&amp;MicroserviceController::handleGet</strong>, this, std::placeholders::_1));<br> _listener.support(methods::PUT, std::bind(&amp;MicroserviceController::handlePut, this, std::placeholders::_1));<br> _listener.support(methods::POST, std::bind(&amp;MicroserviceController::handlePost, this, std::placeholders::_1));<br> _listener.support(methods::DEL, std::bind(&amp;MicroserviceController::handleDelete, this, std::placeholders::_1));<br> _listener.support(methods::PATCH, std::bind(&amp;MicroserviceController::handlePatch, this, <strong>std::placeholders::_1</strong>));<br>}</pre><p>the binding magic of handlers is performed by the <a href="http://en.cppreference.com/w/cpp/utility/functional/bind"><em>std::bind</em></a><strong><em> </em></strong>function template that generates a forwarding call wrapper for a non-static member function, where for all member functions only one argument is required, hence the <em>std::placeholders::_1</em> argument at the end of each declaration.</p><p>Once properly registered our handlers further in the code on the same file <em>microscv_controller.cpp</em> you can see the implementation of each method:</p><pre>void MicroserviceController::handleGet(http_request message) {<br>  auto path = requestPath(message);<br>  if (!path.empty()) {<br>     if (path[0] == “service” &amp;&amp; path[1] == “test”) {<br>        auto response = json::value::object();<br>        response[“version”] = json::value::string(“0.1.1”);<br>        response[“status”] = json::value::string(“ready!”);<br>        message.reply(status_codes::OK, response);<br>     }<br>  }<br>  message.reply(status_codes::NotFound);<br>}</pre><p>in the code above we can see the implementation of the handler for the HTTP method GET. Each time a GET request is issued to the service the http_listener will call this class method on our <em>MicroserviceController </em>class, and the same for each an every handler we register with http_listener.</p><p>The code above is passing the input <em>message</em> through the class method <em>requestPath</em> which basically extracts the request path from the message and returns a <em>std::vector&lt;string&gt;</em> that contains each section of the path so we can evaluate the REST API requested and its input parameters, in this case the request should be something like this:</p><pre>curl -k -i -X GET -H &quot;Content-Type:application/json&quot; <a href="http://192.168.3.176:6502/v1/ivmero/api/service/test">http://&lt;host_ip&gt;:6502/v1/ivmero/api/service/test</a></pre><blockquote>Be aware that the &lt;host_ip&gt; is just a place holder, later in this article I’ll talk about how to specify the endpoint string so the micro-service can automatically resolve the host’s IP.</blockquote><p>and returns a JSON response like this, if the request is successful:</p><pre>{<br> “status” : “ready!”,<br> “version” : “0.1.1”<br>}</pre><p>or an HTTP status code 404 (Not Found) if the request path does not match with any REST API supported by the service:</p><pre>HTTP/1.1 404 Not Found</pre><pre>Content-Length: 0</pre><p>The response is sent back to the caller via the input <em>message</em> instance of type <strong>http_request</strong> which has a reference to the caller.</p><h4>Initializing the service</h4><p>The initialization is located on the <em>main.cpp</em> file so let’s walk through the code:</p><pre>#include &lt;iostream&gt;</pre><pre>#include &lt;usr_interrupt_handler.hpp&gt;<br>#include &lt;runtime_utils.hpp&gt;</pre><pre>#include “microsvc_controller.hpp”</pre><pre>using namespace web;<br>using namespace cfx;</pre><pre>int main(int argc, const char * argv[]) {<br>    InterruptHandler::hookSIGINT();</pre><pre>    MicroserviceController server;<br>    server.setEndpoint(“<a href="http://host_auto_ip4:6502/v1/ivmero/api">http://host_auto_ip4:6502/v1/ivmero/api</a>&quot;);<br> <br>    try {<br>       // wait for server initialization…<br>       server.accept().wait();<br>       std::cout &lt;&lt; “Copyright © ivmeroLabs 2016. ... now listening for requests at: “ &lt;&lt; server.endpoint() &lt;&lt; ‘\n’;<br> <br>    InterruptHandler::waitForUserInterrupt();</pre><pre>       server.shutdown().wait();<br>    }<br>    catch(std::exception &amp; e) {<br>       std::cerr &lt;&lt; “somehitng wrong happen! :(“ &lt;&lt; ‘\n’;<br>    }<br>    catch(…) {<br>       RuntimeUtils::printStackTrace();<br>    }</pre><pre>    return 0;<br>}</pre><p>there are a couple of header files <em>usr_interrupt_handler.hpp </em>which contains code to handle when the user types Ctrl+C on the terminal where the service is running<em> </em>and <em>runtime_utils.hpp</em> that contains code to print the stack trace when an unexpected exception ocurrs. Those files can be found under <em>/micro-service/foundation/include.</em></p><p>In the first line of code we hook on the SIGINT interrupt to handle the Ctrl+C.</p><pre>InterruptHandler::hookSIGINT();</pre><p>Then we create and initialize the service with the endpoint where it will be listening for requests:</p><pre>MicroserviceController server;<br>server.setEndpoint(“<a href="http://host_auto_ip4:6502/v1/ivmero/api">http://host_auto_ip4:6502/v1/ivmero/api</a>&quot;);</pre><p>if you pass <em>host_auto_ip4</em> or <em>host_auto_ip6</em> means the service should auto detect the IP address of the host, if you have more than one network cards it will use the first one it finds in the list of available IP addresses. Then comes the port number and finally the base address of the REST API in this case is <em>/v1/ivmero/api.</em></p><p>Then we initialize the thread pool that is used by pplx concurrency runtime and start accepting network connections:</p><pre>server.accept().wait();</pre><p>after that call if you are runnin on the debugger you’ll see about 40 or so threads on the service process, that constitutes the thread pool hosted by the pplx scheduler. Those threads are pre-spawned to avoid delays when a thread is required and they are re-used during the service life time. So nothing to be scared of. :)</p><p>IMPORTANT: the <em>accept()</em> method returns a <em>pplx::task, </em>but in order to let it perform the creation of the thread pool and initialize the acceptor we have to wait for the task to finish hence the call to the <em>wait() </em>method.</p><p>As soon as the <em>wait()</em> call returns we need to setup a barrier to avoid the process to finish leaving the acceptor to die before any request can be processed, so we call:</p><pre>InterruptHandler::waitForUserInterrupt();</pre><p>which basically is a blocking call that handles the SIGINT and terminates as soon as the user types Ctrl + C on the terminal.</p><p>Finally if the user terminates the process we just shutdown the service and wait for all thread to finish:</p><pre>server.shutdown().wait();</pre><h4>Conclusion</h4><p>As you can see the code is quite simple to implement a C++ micro-service, as simple as a node.js server that exposes a REST interface, in subsequent articles I will continue talking about how to extract the body from a request in JSON format and how to add SSL support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b499ffeaf898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ Development using Visual Studio Code, CMake and LLDB]]></title>
            <link>https://medium.com/@ivan.mejia/c-development-using-visual-studio-code-cmake-and-lldb-d0f13d38c563?source=rss-b2186fbe4ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0f13d38c563</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Iván Mejía]]></dc:creator>
            <pubDate>Tue, 29 Nov 2016 01:49:28 GMT</pubDate>
            <atom:updated>2018-07-06T16:23:21.906Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working for almost a year implementing micro-services on C++11 running as Docker containers. Through my journey I’ve seen to emerge quite a bunch of interesting tools to work with C++ on this field (micro-services and Docker).</p><p>I started using Xcode on Mac OS X (now macOS). Even when Xcode is a fine tool to work on a C++ project, with a very appealing UI and an not a super good debugging experience but useful IMHO, it has a really annoying feature: it is constantly indexing the code while I’m typing it and, in consequence, spinning my MacBook Pro’s fans up to 5000 rpm and making it really hot. I tried disabling all code completion options in <strong>preferences</strong> without any success. This made me think about returning to Emacs which, even when I used it in the past, I would say I’m not an expert and re-loading it in my brain will take me some time to interiorize the shortcut keys and so on, so I thought about looking for something similar but modern, for that I passed through TextMate, Atom, Sublime and <a href="https://code.visualstudio.com/?utm_expid=101350005-35.Eg8306GUR6SersZwpBjURQ.0&amp;utm_referrer=https%3A%2F%2Fwww.google.com.mx%2F">Visual Studio Code</a>.</p><p>Visual Studio Code (VSC from now on) has a similar idea as Emacs has, to provide a very simple editing tool but powerful at the same time providing the full development cycle (editing, building and debugging all inside the tool). It runs with native performance on Windows, OS X and Linux and with a very adaptive UI that looks and feels native to the OS where it runs, which is a plus.</p><p>At the time I started working on my micro-services project, VSC was quite new and there was not full support for C++ except for the syntax coloring and some very experimental integration with GDB and LLDB, but today after less than a year VSC is quite operational on the C++ development cycle, you can integrate it with CMake and build a C++ project from inside VSC and not only to use CMake but to use a C++ Debugger (GDB or LLDB) inside VSC.</p><p>So this article is about the steps I followed to configure VSC to work with C++, CMake and LLDB.</p><h3>Prerequisites</h3><ul><li>A C++ compiler already installed, whether it is <strong>clang</strong> or <strong>gcc</strong>. In my case I have already installed Xcode that I use for my iOS projects so is convenient, but if you are only interested on pure C++ you can install any of the previously mentioned or both.</li></ul><p><strong>Installed Visual Studio Code:</strong></p><ul><li>Download VSC <a href="https://code.visualstudio.com/?utm_expid=101350005-35.Eg8306GUR6SersZwpBjURQ.0&amp;utm_referrer=https%3A%2F%2Fwww.google.com.mx%2F">from here</a></li><li>Open VSC</li><li>Launch VS Code Quick Open (⌘+P) and paste the following commands, then press enter.</li></ul><p><strong>To Install the Microsoft C/C++ extension:</strong></p><ul><li>ext install cpptools</li></ul><p><strong>To Install CMake extension:</strong></p><ul><li>ext install cmake</li></ul><p><strong>Install Native Debug extension:</strong></p><ul><li>ext install debug</li></ul><h3>Let’s get started by creating a workspace in VSC</h3><p>Create a directory where your project will reside let’s say (in a very informal way) ~/Desktop/hello-vsc and open that directory on VSC (Command + O):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YM9v2kPMglo1I55LoMnhg.png" /></figure><p>Now add the files:</p><ul><li>CMakeLists.txt</li><li>hello_vsc.cpp</li></ul><h3>Now lets write some code</h3><p>In case you wonder, CMakeLists.txt is the input file of CMake. CMake is a command line tool used to control the software compilation process and it can be used for cross-platform software development. So in micro-services land is key to be cross-platform and as of today C++ is the greatest cross-platform language of all.</p><p>So let’s type the following code inside our CMakeLists.txt file:</p><pre>cmake_minimum_required(VERSION 3.0)</pre><pre>project(hello-vsc)</pre><pre>set(SOURCE hello-vsc.cpp)</pre><pre>add_executable(${PROJECT_NAME} ${SOURCE})</pre><p>where we first make sure to use as minimum version of cmake the 3.0, then we set the project’s name to “hello-vac”, next we say that the source code of our project is in “hello-vsc.cpp”, here you can add more files separated by one or more spaces and finally we set our executable’s using the same name we use as the project name and declaring the sources code to be included during the build process. So that’s it for CMake, in case you want to know more about CMake, <a href="https://www.johnlamp.net/cmake-tutorial-1-getting-started.html">these are excellent tutorials.</a></p><p>Now on “hello-vsc.cpp” type the following simple C++ code and save it:</p><pre>#include &lt;iostream&gt;</pre><pre>int main(int argc, const char * argv[]) {<br>    std::cout &lt;&lt; &quot;hello Visual Studio Code! :)&quot; &lt;&lt; &#39;\n&#39;; <br>    return 0;<br>}</pre><p>Now on the editor you will notice a green squiggle under the first and only #include statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTIE7YmWZwgVxL_whM69sw.png" /></figure><p>that means VSC cannot find the included file in this case <strong>iostream, </strong>so we need to generate the file c_cpp_properties.json file and in order to do that just:</p><ul><li>click on the lightbulb that appears on the left side</li><li>click <strong>Add include path to settings.</strong></li></ul><p>you will be presented with a file with the following JSON source:</p><pre>{<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Mac&quot;,<br>            &quot;includePath&quot;: [&quot;/usr/include&quot;],<br>            &quot;browse&quot; : {<br>                &quot;limitSymbolsToIncludedHeaders&quot; : true,<br>                &quot;databaseFilename&quot; : &quot;&quot;<br>            }<br>        },<br>        {<br>            &quot;name&quot;: &quot;Linux&quot;,<br>            &quot;includePath&quot;: [&quot;/usr/include&quot;],<br>            &quot;browse&quot; : {<br>                &quot;limitSymbolsToIncludedHeaders&quot; : true,<br>                &quot;databaseFilename&quot; : &quot;&quot;<br>            }<br>        },<br>        {<br>            &quot;name&quot;: &quot;Win32&quot;,<br>            &quot;includePath&quot;: [&quot;c:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include&quot;],<br>            &quot;browse&quot; : {<br>                &quot;limitSymbolsToIncludedHeaders&quot; : true,<br>                &quot;databaseFilename&quot; : &quot;&quot;<br>            }<br>        }<br>    ]<br>}</pre><p>given that this article is focused on Mac OS X, we will use the section labeled <strong>“name”: “Mac”</strong>, but what we’ll do here should be applicable to the other platforms.</p><p>The c_cpp_properties.json file generated is enough for this article but if you require to use other third party libraries, the <strong>“includePath”</strong> array is the place to add more paths so VSC can provide auto completion information.</p><h3>Generating Tasks for CMake and Make</h3><p>On VSC type ⇧+⌘+P and type “Tasks”, then select the one with the name “Configure Task Runner”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLxX0q10X8xPrMjccoQavg.png" /></figure><p>from the list pick the one labeled as “Others”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7zwBNA2nAjs8wQQVsJICQ.png" /></figure><p>that’ll generate the “tasks.json” file that looks as follows:</p><pre>{<br>    // See <a href="https://go.microsoft.com/fwlink/?LinkId=733558">https://go.microsoft.com/fwlink/?LinkId=733558</a><br>    // for the documentation about the tasks.json format<br>    &quot;version&quot;: &quot;0.1.0&quot;,<br>    &quot;command&quot;: &quot;echo&quot;,<br>    &quot;isShellCommand&quot;: true,<br>    &quot;args&quot;: [&quot;Hello World&quot;],<br>    &quot;showOutput&quot;: &quot;always&quot;<br>}</pre><p>a task file allows you to add command that can be executed from the shell in the example above generated the tasks.json file executes the command “echo” and pass it as argument “Hello World”. To execute it just type:</p><ul><li>⇧+⌘+P and type “Tasks” again, but this time select the option labeled as “Run Task”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0s0bx7OgNeuMq6L8zTFbw.png" /></figure><ul><li>Select only item in the list labeled as “echo” and you will see the output at the bottom of the editor:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZT8FX5-R9afheMMC6pH_qQ.png" /></figure><p>More on tasks <a href="http://code.visualstudio.com/docs/editor/tasks">here</a></p><p>so now let’s do something more interesting, let’s modify the tasks.json file as follows:</p><pre>{<br>    // See <a href="https://go.microsoft.com/fwlink/?LinkId=733558">https://go.microsoft.com/fwlink/?LinkId=733558</a><br>    // for the documentation about the tasks.json format<br>    &quot;version&quot;: &quot;0.1.0&quot;,<br>    &quot;command&quot;: &quot;sh&quot;,<br>    &quot;isShellCommand&quot;: true,<br>    &quot;args&quot;: [&quot;-c&quot;],<br>    &quot;showOutput&quot;: &quot;always&quot;,<br>    &quot;<strong>options</strong>&quot;: {<br>        &quot;<strong>cwd</strong>&quot;: &quot;${workspaceRoot}/build&quot;<br>    },<br>    &quot;<strong>tasks</strong>&quot;: [<br>        {<br>            &quot;taskName&quot;: &quot;<strong>cmake</strong>&quot;,<br>            &quot;args&quot;: [&quot;cmake -G &#39;Unix Makefiles&#39; -DCMAKE_BUILD_TYPE=Debug ..&quot;]     <br>        },<br>        {<br>            &quot;taskName&quot;: &quot;<strong>make</strong>&quot;,<br>            &quot;args&quot;: [&quot;make -j 8&quot;],<br>            &quot;isBuildCommand&quot;: true            <br>        }<br>    ]<br>}</pre><p>the interesting part in our case is the the <strong>“options”</strong> section where is used the property <strong>“cwd”</strong> (current working directory) and the substitution variable “<strong>${workspaceRoot}</strong>”, this variable contains the path to the folder where we load our project in VSC. We concat the “<strong>build</strong>” directory which should be created under our project’s root directory:</p><pre>$ cd hello-vsc<br>$ mkdir build<br>$ ls -l</pre><pre>-rw-r--r--  1 ivanmejia  staff   125B Nov 28 08:41 CMakeLists.txt<br>drwxr-xr-x  6 ivanmejia  staff   204B Nov 28 08:42 <strong>build</strong>/<br>-rw-r--r--  1 ivanmejia  staff   136B Nov 28 10:44 hello_vsc.cpp</pre><p>then the property “<strong>tasks</strong>” is an array of tasks we require, in this case the task “<strong>cmake</strong>” which allows us to generate all the build files required to generate a binary executable; in this case we and the task “<strong>make</strong>” that allows us to build our executable.</p><p>Finally the property “<strong>isBuildCommand</strong>” set to true enables the task to be executed via the <strong>Tasks: Run Build Task.</strong></p><p>Now to run the “<strong>cmake</strong>” do the following:</p><ul><li>⇧+⌘+P and type “Tasks” and pick <strong>“Run</strong> <strong>Task</strong>”</li><li>From the list pick “<strong>cmake</strong>” and you’ll see the following output</li></ul><pre>Usage<br>  cmake [options] &lt;path-to-source&gt;<br>  cmake [options] &lt;path-to-existing-build&gt;<br>Specify a source directory to (re-)generate a build system for it in the<br>current working directory.  Specify an existing build directory to<br>re-generate its build system.<br>Run &#39;cmake --help&#39; for more information.</pre><p>that means we are not passing correctly the arguments, that’s why we need another property called “<strong>suppressTaskName</strong>” (in tasks.json file above) and set it to true, that’ll suppress the task name to be passed as part of the task and instead passing the arguments of the task, which for the case of “<strong>cmake</strong>” are:</p><pre>-G &quot;Unix Makefiles&quot; -DCMAKE_BUILD_TYPE=Debug ..</pre><p>which basically instructs CMake to generate the build files and set it up to instruct the C++ compiler to avoid using optimizations and generate debug code; finally the “..” indicate to use the ../CMakeLists.txt file as the input of CMake.</p><p>The arguments for the “<strong>make</strong>” task are:</p><pre>-j 8</pre><p>basically instructs make to start building our program and use 8 jobs that can run simultaneously in each core of your computer’s CPU, even when in this case this argument is not necessary you can leave it in case you have more than 8 source files, that’ll make the compiler to compile all the sources in parallel assigning each source to one core and leaving the rest to other cores as soon as they get free of work.</p><p>So set “<strong>suppressTaskName</strong>” to true:</p><pre>{<br>    // See <a href="https://go.microsoft.com/fwlink/?LinkId=733558">https://go.microsoft.com/fwlink/?LinkId=733558</a><br>    // for the documentation about the tasks.json format<br>    &quot;version&quot;: &quot;0.1.0&quot;,<br>    &quot;command&quot;: &quot;sh&quot;,<br>    &quot;isShellCommand&quot;: true,<br>    &quot;args&quot;: [&quot;-c&quot;],<br>    &quot;showOutput&quot;: &quot;always&quot;,<br>    &quot;<strong>suppressTaskName</strong>&quot;: true,<br>    ...</pre><pre>}</pre><p>and again type ⇧+⌘+P and type “Tasks” and pick <strong>“Run</strong> <strong>Task</strong>” and now you should see an output like this:</p><pre>-- The C compiler identification is AppleClang 8.0.0.8000042<br>-- The CXX compiler identification is AppleClang 8.0.0.8000042<br>-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc<br>-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works<br>-- Detecting C compiler ABI info<br>-- Detecting C compiler ABI info - done<br>-- Detecting C compile features<br>-- Detecting C compile features - done<br>-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++<br>-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works<br>-- Detecting CXX compiler ABI info<br>-- Detecting CXX compiler ABI info - done<br>-- Detecting CXX compile features<br>-- Detecting CXX compile features - done<br>-- Configuring done<br>-- Generating done<br>-- Build files have been written to: /Users/ivanmejia/Desktop/hello-vsc/build</pre><p>now we have all the files necessary to build our project under our ./build directory.</p><ul><li>Now again type ⇧+⌘+P and type “Tasks” and but this time pick <strong>“Run Build</strong> <strong>Task</strong>”</li><li>From the list pick “<strong>make</strong>” and you should see the following output:</li></ul><pre>Scanning dependencies of target hello-vsc<br>[ 50%] Building CXX object CMakeFiles/hello-vsc.dir/hello_vsc.cpp.o<br>[100%] Linking CXX executable hello-vsc<br>[100%] Built target hello-vsc</pre><p>now on your terminal window go to ./hello-vsc/build and type the executable’s name and you should see it output:</p><pre>$ ./hello-vsc<br>hello Visual Studio Code! :)</pre><p>So there you have your code being buld through CMake from within VSC.</p><h3>Now let’s debug our code using LLDB inside VSC.</h3><p>We need to configure our project to use the debugger so let’s follow these simple steps:</p><ul><li>On VSC click on the little bug icon on the Sidebar</li><li>Click the Configure Icon on the Debug View (the little gear with a red badge on it):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGAvtjjptVB0aVP8V0gNWA.png" /></figure><ul><li>From the list select LLDB (these steps apply for other C/C++ debuggers as well). That’ll generate a new file called launch.json. By the way, in case you wonder where all these files (c_cpp_properties.json, tasks.json and launch.json) are stored, if you look on your terminal you will see a ./.vscode directory, which is where all those files are stored.</li></ul><pre>$ .<strong>/hello-vsc/.vscode</strong>$ ls -l</pre><pre>total 24</pre><pre>-rw-r--r--  1 ivanmejia  staff   771B Nov 28 10:15 c_cpp_properties.json<br>-rw-r--r--  1 ivanmejia  staff   250B Nov 28 15:45 launch.json<br>-rw-r--r--  1 ivanmejia  staff   625B Nov 28 15:28 tasks.json</pre><ul><li>Your new generated launch.json file should look like this:</li></ul><pre>{<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Debug&quot;,<br>            &quot;type&quot;: &quot;lldb-mi&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;<strong>target</strong>&quot;: &quot;./bin/executable&quot;,<br>            &quot;cwd&quot;: &quot;${workspaceRoot}&quot;<br>        }<br>    ]<br>}</pre><ul><li>Let’s modify the “<strong>target</strong>” property like this:</li></ul><pre>&quot;<strong>target</strong>&quot;: &quot;./bin/hello-vsc&quot;</pre><p>that’ll make the debugger run and attach to our executable inside VSC.</p><ul><li>Finally you need to add to your PATH the location of the lldb-mi dibbuger, which in case you have Xcode installed should be:</li></ul><pre>/Applications/Xcode.app/Contents/Developer/usr/bin/</pre><ul><li>once you add to your PATH on your .bash_profile the location of the lldb-mi debugger just re-launch VSC and you should be able to debug your code by just clicking the “<strong>Start Debugging (F5)</strong>” button in the Debug View:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1M4-rBDZ2kpaSiTaItCh9w.png" /></figure><p>So this is it, you have a C++ project being build with CMake and Debugged using LLDB on Mac OS X all inside Visual Studio Code. I hope this helps you.</p><p>I had to dig into various places to come with this solution and finally this looks promising as a confortable cross-platform development environment for C/C++ developers like me. 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0f13d38c563" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>