Sunday, July 22, 2012

Getting Started with Waf to Build C/C++ Applications

Waf is another build tool like SCons. It's a fork of SCons that is more Pythonic than SCons. Here is a simple example how to get build a C++ application with Waf.
waf-project
├── include
│   └── Hello.h
├── src
│   ├── Hello.cpp
│   └── Main.cpp
└── wscript
Hello.h
#ifndef HELLO_H_
#define HELLO_H_

class Hello {
public:
    void sayHello();
};


#endif /* HELLO_H_ */
Hello.cpp
#include <iostream>
#include "Hello.h"
using namespace std;

void Hello::sayHello() {
    cout << "Hello World" << endl;
}
Main.cpp
#include "Hello.h"
using namespace std;

int main() {
    Hello h;
    h.sayHello();

    return 0;
}

wscript
#!/usr/bin/env python

APPNAME = 'waf-project'
VERSION = '0.1'

top = '.' 
out = 'build'

def options(ctx):
    ctx.load('compiler_cxx')
    ctx.add_option("--shared", action="store_true", help="build shared library")
    ctx.add_option("--static", action="store_true", help="build static library")
    
def configure(ctx):
    ctx.load('compiler_cxx')

def build(ctx):
    if ctx.options.shared:
        ctx.shlib(source="src/Hello.cpp", target="hello", includes=["include"],
                  cxxflags="-g -Wall -O0")
    elif ctx.options.static:
        ctx.stlib(source="src/Hello.cpp", target="hello", includes=["include"],
                  cxxflags="-g -Wall -O0")
    else: # by default, build a shared library
        ctx.shlib(source="src/Hello.cpp", target="hello", includes=["include"],
                  cxxflags="-g -Wall -O0")
        
    ctx.program(source="src/Main.cpp", target="main", includes=["include"],
                use="hello")
waf configure
This will create all the configuration files in a "build" directory as specified in the out variable.
waf configure build --static
This will create a "hello" static library and a "main" program that is statically linked with the "hello" static library. The static library and the program will be created in a "build" directory as specified in the "out" variable.
waf configure build --shared
This will create a "hello" shared library and a "main" program that is dynamically linked with the "hello" shared library. The shared library and the program will be created in a "build" directory as specified in the "out" variable.

No comments:

Post a Comment