Posts mit dem Label programming werden angezeigt. Alle Posts anzeigen
Posts mit dem Label programming werden angezeigt. Alle Posts anzeigen

Dienstag, 1. Oktober 2013

My idea of how make should be done

Welcome dear reader!

When I start spending time with a new programming language, I usually want to get a clear picture first of how my workflow should look like. I simply want to do it right from the beginning, using state-of-the-art tools and profiting from others' experiences, so I will be able to work efficiently right away and so that my project evolves around a good structure.

Currently, I am trying out C++ (not for the first time, but this time for real), denying myself using an IDE which would get me started quickly but rendering me entirely planless of what is going on behind the scenes.
Naturally, I was confronted right at the beginning with the decision which build system to use. I started out using the best known one, gnu make, and got comfortable with it. Actually it was even so good, that when I decided to go for cmake instead (which seems to be next to autotools the only  relativley widespread build tool out there), I couldn't tell any improvements over make.

So here I want to give you an overview of the conclusions I've drawn about how to use makefiles in a project-independent, yet absolutely clean manner:

  1. of all: The project's top-level structure:
    I wanted a clean top-level project directory with nothing in it but introductory documentation (license, readme...), one folder for source (src) and one to build into (build). Lateron, looking into other projects, I also saw that being able to offer support for several other (maybe ide-specific) build systems would be great, too, so I decided to give each one of them a separate directory - "Make" doing the first step here.
    That leads us getting something like:
    • project root
      • build
      • src
      • Make
      • ...
      • XCode/Eclipse etc.
    This way we can also strictly keep the build-tool related files from our code, as another positive sideeffect.

  2. how to even make it work:
    Now that we have decided to put all our makefiles into the Make directory, how will make get to see the files it has to build together? It is not even in the project's root directory. That's why we need to get this root directory first - the parent of the folder, our makefile resides in:
     ROOTDIR            = $(realpath $(dir $(realpath $(dir $(lastword $(MAKEFILE_LIST))))))  
    
    I am using here, that calling "realpath" on a directory name will cause the original path to be stripped of trailing slashes. Therefore, another call of "dir" on it will give me the parent directory. I know, this is somewhat hacky, but we just won't mind.
    So next thing is to export our ROOTDIR variable, so that all other makefiles can use it et voilà: Accessing specific directories far away from our "Make" directory won't be a problem any more.

  3. how to reuse our makefiles:
    I far as I could see, it is very common to extend a build system as the actual project grows with the time. The downside of this procedure is obvious: Makefiles written this way tend to be project specific and can hardly be reused. So we need ways to separate project specific attributes from the reoccuring parts of a makefile.
    First thing I'd recommend here is a dedicated defs.mk makefile containing all or most of your definitions. This way you will have all your project-dependent stuff just there and this will be easy to understand for external collaborators. Note that my make_boilerplate contains a nice draft of such a defs.mk file which you can use and modify as you like to.
    In the future, we will just include our definition file to gain access to our whole project's configuration:
     include $(ROOTDIR)/Make/defs.mk  
    
    Yes, I do know about the "MAKEFILES" environment variable, but I think, this way it is just more transparent. So let's just do it this way.

  4. recursive makefiles(?):
    Coming from Java WITH IDEs, I had a pretty detailed vision of how I wanted my project to be structured. Over all, folders play a central role in dividing pieces of code into single units of related functionality. But how to tell make that those source files, distributed over several hierarchies of folders, have to be built into one single binary?

    Recursive makefiles - while seeming obvious at first (icu, for example, is doing it this way) - didn't comply with my ideas stated above, since they had to lie in the source directory. Additionally, it relatively quickly turned out, that recursive use of makefiles is actually not desireable. Click here for details.

    So I went for good old "find" to get my .cpp files which I would then turn into a list of .o files:
     CXXFILES       = $(shell find $(SRCDIR) -type f -name '*.cpp')  
     CXXOBJECTS     = $(patsubst $(SRCDIR)/%.cpp,$(OBJDIR)/module/%.o,$(CXXFILES))  
    
    Those, as you can see, I put into their respective subdirectory in my object build directory.

  5. where to divide makefiles:
    When working with makefiles in a project, you often have them grow according to your needs while you are concentrating on your code. Therefore one often ends up having huge and unreadable makefiles that are likely to break on minimal changes. I suggest the following here: Have one makefile for each big part of your project. This will not contradict our earlier statement "recursive make considered harmful", since the makefile is still as self-contained as possible and should not call any sub-makes either. We just use the modularity of our project to have clean cuts. I suggest one makefile for every lib or binary of your own project, maybe one makefile for each of your dependencies if they have to be built from source or one single makefile together for all your prebuilt libraries.
    Standard targets that can be "outsourced" include:
    • deps.mk (for dependencies)
    • tests.mk
    • <projectname>.mk for your project

  6. handling indirect dependencies:
    We know that make works using a file's dependencies to create the file itself, if those are newer. Therefore we have to specify the dependencies, which we already automated. But we completely left out the fact, that header files included in our .cpp files are also dependencies.
    In order to be able to respond to changes made to only those included files, we will use a trick which I borrowed from here: We exploit the -M option (for gcc and similar), which gives us all files included by a codefile and write them into a seperate makefile, which we will include from now on. These secondary makefiles we will be giving the suffix ".d", as in "dependency". So the rule for .o files will be looking like 
     $(OBJDIR)/%.o: $(SRCDIR)/%.cpp  
         @mkdir -p $(dir $@)  
         @$(COMPILE.cxx) $@ $^  
         @# Create the .d file using gcc's -M or -MM option  
         $(CXX) $(CPPFLAGS) $(CXXFLAGS) -MM $(lastword $^) > $(patsubst %.o,%.d,$@)  
    
    Additionally, we will have to retrieve the existing .d files at the beginning of our makefile and include them:
     DEPFILES        = $(CXXOBJECTS:.o=.d)  
     -include $(DEPFILES)  
    
    The "-" in front of include turns off errors on file-not-found. And that's it!
    Make sure though that you include the DEPFILES only after the "all" target, so some object file won't become your default target.

  7. coping with different levels of verbosity:
    In general it has to be said, that make's philosophy can be a bit obstructive when it comes to communicating what is going on. First of all, there is no parse-time option to output messages to the console. Trying it with approaches like "$(shell echo some message)" will fail because make' s goal here is it to grab the shell command's output. So you will not be able to just dump all variable values of interest on make startup before a target is built. You will rather have to have an own "info" target doing that, which is prerequisite of your "all" target or you are calling yourself.

    The next problem is, that when you have a simple target that just aggregates other tasks, and you want to announce its start and its end, at least the first of those two cannot be achieved. For example, imagine you want to make sure, all build directories are set up correctly in target "directories: dir1 dir2 dir3". Where will you put the "Start creating directories" message? You will have to live with that limitation or invent a smart way to avoid this.

    To have control over what is printed and when, I suggest setting up variables like "PRINT" (echoing always) and "VPRINT" (echo if in verbose mode, otherwise just /bin/true). This can be extended to "VVPRINT" (VERBOSE = 2) etc. if necessary.
    Additionally, the make variable "MAKECMDGOALS" can be helpful to detect if the user ran make with the intention of getting more information as usual about the build process. I, for example, did the following right at the beginning of my main Makefile: 
     ifeq ($(filter info, $(MAKECMDGOALS)),info)
         VERBOSE = YES
         export VERBOSE # for all sub-makes
     endif
    
On these thoughts as a basis, I set up a small github repository I called "make_boilerplate". You will find it by following https://github.com/suluke/make_boilerplate . Maybe things will also be clearer if you take a look into the makefiles themselves.

I've been reading lots and lots of articles and stackoverflow questions on the internet to get all this done in a way I personally can live with. I don't guarantee you, though, that it is bugfree or even trapless. I see a high chance that some professional with 40 years of experience shows up and tells me about a bunch of flaws my makefile design comes with. Personally I don't see any problems so far though - and this is why I posted this. I hope, you will find it helpful, too.

Regards

suluke


Sources:

Sonntag, 21. April 2013

Dark theme for Eclipse Juno on dark Xfce in 3 steps

[EDIT 2013/11/08]
In the meantime, Eclipse Kepler was released and I have moved to an Eclipse installation via Arch User Repository. I do not know which of both broke my guide, but I really couldn't get it to work any more, so I checked the web again and found THIS "install-new-software"-installable theme via Stackoverflow. To turn it on, go the same way as before (Window->Preferences->General->Appearance).

Hey folks!

Since I had to spend some time googling again to make this work, I thought I'd just write down the necessary steps for some of you.

Actually it is pretty easy to "dark theme" eclipse juno when knowing how to:
  1. Install "dark juno" by Roger Dudler from here by
    1. Downloading the plugin zip file
    2. Extracting the "plugin" folder from the zip with its contents to <eclipse installation directory>/dropins/
    3. (Re-)starting Eclipse
    4. Navigating to Window->Preferences->General->Appearance and choosing "Dark Juno" in the dropdown
  2. Install the Eclipse Color Theme from the Eclipse Market
  3. Look for a nice theme on http://eclipsecolorthemes.org/ and apply it via Window->Preferences->General->Appearance->Color theme
That should be it. My result (with Color theme "Zenburn") looked like this:

Happy coding!

Dienstag, 22. Mai 2012

Show a preview of your latest blogspot post on your external domain homepage

Hello readers!


During my internship I was given the task to find out on how to realize a small preview of the newest post from a blog here on blogspot. The problem was, that the previews should be integrated into a website owned by our client which was hosted by a different provider on a different domain, and that they should always keep up to date without any modifications. Additionally, my boss preferred to have the preview generated on client side, because it means less traffic and probably less trouble when integrating it into the rest of the framework-based project. In plain words, I was supposed to use Javascript.

So I searched the internet for multiple keyword combinations but did not find any solutions of someone who did that before. So I had to come up with a solution myself.

I believe there are three possible approaches for that:
The worst should be to go via the blog homepage, because then the desired information would either be mixed up with all sort of additional markup or completely hidden in other js-scripts.

The second approach is probably the most elegant one, but not completely simple to realize: If I tried to receive the data by pulling it from the blog's atom/rss feed I would have my information in a relatively good structure and Google would probably not set a limit to the number of accesses per day. Unfortunately though, plain javascript does not provide tools to parse the xml-alike feed output and I did not want to mess with an external library or parse the feed myself, which is probably still relatively easy with regular expression matches.

But I went the third way, which is probably the first one that came to your mind: Via the blogger api.
The api is currently under construction (heading for version 2) and the registration process takes some time to complete. You have to register/create a new api-Project on https://code.google.com/apis/console/ and apply for the permission to use the blogger api in it. The response e-mail took about twelve hours during the two times I tried it, which is the reason why I even think that there is only one Google employee who manually admits the usage of the api for your project.

Afterwards you simply do what the blogger-team wrote in their answer and you get access to the API-key, which is used by Google to keep track of your usage. I believe, the standard daily quota is about 1000 and I hope, it is counted by IPs and not by API-calls. Otherwise the permitted accesses would be exhausted quite rapidly.

Here is the code of my blogger.js file that generates the preview:
 /**  
  * Version: 2012/05/23 rev.1  
  *   
  * This script obtains information from the first post of a blogger-blog   
  * (in particular title + first image) and injects it into a specific  
  * place in the webpage.  
  *   
  * Currently, the information is written into an element (<div>) with the  
  * ID "blogger_output"  
  *   
  * To be able to style the information via css, the following classes are given to it:  
  * post title (p-tag): blogger_title  
  * post image (img-tag): blogger_image  
  */  
   
 function Blogger() {  
    Blogger.init();  
 }  
   
 Blogger.htmlOut = "blogger_output"; //The html-element, in which the blog-preview is to be written  
 Blogger.gAPI_URL = "https://www.googleapis.com/blogger/v2/blogs/"; //the blogger api base-url  
 Blogger.blogID = "9034413279324519603"; //The id of the blog whose latest post we want to generate a preview from  
 Blogger.apiKey = "AIzaSyCYuAlcd4NzcvTB2Igp7b2Tuuak_mLfcfk"; //The api-key to access the blogger-api  
   
 /**  
  * Writes a new line of (html-) text into the output element specified above  
  * @param text Some text to be written into the htmlOut element  
  */  
 Blogger.echo = function(text, writeInID) {  
    document.getElementById(writeInID).innerHTML += text;  
 };  
   
 /**  
  * Dynamically injects a script to the end of the body of the page  
  * @param jsname the url or name of the script to be injected  
  */  
 Blogger.injectScript = function (jsname) {  
    var scr = document.createElement('script');  
    scr.setAttribute('type','text/javascript');  
    scr.setAttribute('src',jsname);  
      
    var body = document.getElementsByTagName('body')[0];  
    body.appendChild(scr);  
 };  
   
 /**  
  * This is the callback method of the first blogger api call. Currently it does all  
  * the work (get title, image(s), preview text...), but at a later point we hope  
  * the blogger REST-api will support at least images as an additional resource type.   
  * In this case it is easy to add a second callback method correponding to the image[s]  
  * of the first post only.  
  * @param response The response of the google server after our api call  
  */  
 Blogger.handleBlog = function(response) {  
    //extract image url  
    var imgTag = response.items[0].content.match('(\\u003cimg.*?(/\\u003e))')[0];  
    var imgUrl = imgTag.match('http:.*?(?=\")');  
      
    //output  
    var aName = "blogger_link";  
    this.echo('<a id="' + aName + '" class="' + aName + '" href="' + response.items[0].url + '"></a>', this.htmlOut);  
    this.echo('<p class="blogger_title">' + response.items[0].title + '</p>', aName);  
      
    //Maybe a post has no image  
    //TODO: In this case, other information from the post could be shown  
    if(imgUrl != null) {  
       this.echo('<img class="blogger_image" alt="" src="' + imgUrl + '"/>', aName);  
    }  
    this.echo('</a>');  
 };  
   
 /**  
  * The first method of the script.  
  */  
 Blogger.init = function() {  
    //Inject script to obtain blog-data from google/blogger  
    var callback = 'Blogger.handleBlog';  
    var jsname = this.gAPI_URL + this.blogID + '/posts?callback=' + callback + '&key=' + this.apiKey;  
    this.injectScript(jsname);  
    return;  
 };  
   
   
 Blogger();  

Of course, you have to replace the values of the variablesapiKey and blogID with your personal data.

There are two techniques used here that may require explanation for beginners:
First, the data is received in JSON format via JSON with Padding (JSONP). You will easily find guides on this by using the internet.
And secondly there is the dynamic javascript injection in injectScript, which I borrowed from http://javascript.about.com/library/bladdjs.htm.

Additionally, there are a few things that I wanted to comment on here:
First thing is: please don't forget that I am an intern and this is actually my first try in anything javascript related. This is my first attempt of a pure js version.

You can also find a version of this script as a jquery-plugin under http://dl.dropbox.com/u/19826318/Blogger/bloggerJQP.js
In this case, only jquery has to be loaded, followed by the script call.

Secondly, you might have seen some passages in the code which refer to the current status of the blogger api. I really hope, there will be some improvement there as far as resource types are concerned. At least, the developer in charge has already received and approved a feature request upon this.

The code is well documented I hope, and there are classes/IDs given to the output later on which allow easy CSS-styling.

Used in a website, the html might look like the following:
1:  <html>  
2:   <head>  
3:    <title>JavaScript-Test</title>  
4:   </head>  
5:   <body>  
6:    <div id='blogger_output'><p>Neues aus meinem Blog:</p></div>  
7:    <script src="blogger.js" type="text/javascript"></script>  
8:   </body>  
9:  </html>  
...where the <div>-tag's id "blogger_output" is required for the script to be able to write the content into.

Result: 
Title and image of the post, all linking to the original post-url
Title and image of the post, all linking to the original post-url

I hope, this might be useful for some web-developer or intern out there. Please leave a comment if you liked it or if you have suggestions on how to improve this:)

See you soon,
suluke







Helpful links:
Getting started of the blogger JSON api 2.0
Code formatter for blogger

Mittwoch, 8. Februar 2012

Fibonacci in batch

Here a simple programm showing some of the power of batch, just so you get an impression why I think it is a good start to learn how to program:
Fibonacci.bat
1 :: This script prints out all Fibonacci-numbers up
2 :: to a position defined by the user
3 :: Version 1.0
4 :: Date: 2012/01/26
5 :: Author: Lukas Boehm
6 @echo off
7
8 :: Section that asks the user to enter a VALID
9 :: position in the fibonacci-sequence
10 setlocal
11 :input
12 set /p POS=Bitte geben Sie die gewuenschte Stelle in der Folge ein
13 set /a NUM=%POS% + 0
14 echo.
15 if %NUM% neq %POS% (
16 echo Fehler: keine gueltige Zahl!
17 goto input
18 )
19 endlocal & set POS=%POS%
20
21 :: Section that calculates and prints out
22 :: the fibonacci numbers
23 setlocal EnableDelayedExpansion
24 set LAST=0
25 set CURRENT=1
26
27 FOR /L %%N IN (1, 1, %POS%) DO (
28 set SWAP=!CURRENT!
29 set /A CURRENT +=!LAST!
30 echo !LAST!
31 set LAST=!SWAP!
32 )
33 endlocal
34
35 :EOF
36 PAUSE

Sonntag, 22. Januar 2012

Initial commit - the "succeed first - develop interest - learn on-the-fly"-approach


Hello there!
I am a self-taught programmer from Germany and really love programming. It gives me some feeling comparable to the one a gardener has when he has worked a lot on his plants and finally he can harvest the results of his work. The only difference is that I don't need to be on the field all day and everything happens much faster than waiting for plants to grow. Besides, the work rather challenges your brain than your muscles.

The benefit of the ability to code a bit are quite obvious, so I often feel the desire to share my skills and help others with them. But teaching programming on the fly is definitely not as easy as some might think. First of all, your apprentice must be willing to spend some time at least. Second, you will have to have a master plan on how you want to progress. I have made the experience that just because I started with learning java, this is not a good way to start with newbies who expect to be given a gentle introduction. Already setting up jdk with environment variables, and maybe eclipse and so on is far too much for the first day. And the first day is decisive for the first impression of the learner and whether he believes that he will be able to learn it or not. Therefore I believe a person who wants to become a part-time programmer has to start with the means that are already installed on his machine. But which means ARE installed on his machine?

Well, many pc-users out there are using M$ windoze. Unfortunately though, this os does not come along with any compilers or anything similar, so everytime I want to simply type in a "hello world" to deliver quick success to my prentice, the only possibility to do this is to use one of the two scripting interfaces windows features, namely batch and visual basic script (and maybe html, but I don't know whether this is a good idea to start with. I mean, maybe this will make our friend who wants to learn programming a bit confused since usually noobs cannot imagine that IE does something locally. In addition, ui/graphics programming is a far step further down the road. If you really want to program on hardware level, fency graphics will only prevent you from getting lower to the system. But I will keep this in mind for the next time)

Batch is fairly easy to get started with since there is so little to learn and everything seems to be kind of self-explanatory. But on the other hand batch is very limited. I would even say, it is very VERY limited. Already when you come to arithmetics, you will see that it is originally designed to perform some file system tasks, since you will need the switch "/a" in front of every mathematic assignment. And it is nothing that can be compared to any other modern programming language. You have no code blocks, no functions, no types, and you have GOTO. Except that, batch will serve perfectly well to introduce an absolute beginner to the main idea behind programming:
Tell the computer what you want within a limited set of commands and never expect him to do anything intelligent on his own.

To conclude, using batch has the advantages that it works out of the box and features almost everything you will want to do in the first coding lessons. That is hello world, importance of commenting and some simple calculation etc. without the trouble of compiling or installing interpreters.
Critics will say, that batch has nothing to do with programming (and I will agree with them) and will damage the style of the later programmer (and here I will disagree. In my opinion only the one who knows ugliness is able to become aestheticist ;-)

So far so good, that was my first blog post.
See you soon