0%

前一陣子在做C++轉C Code的動作,真是麻煩的苦工。 在看到Modern C++ in embedded systems – Part 1: Myth and Reality還真是心有慼慼焉啊。C++能做的,C當然也可以,不過程式可讀性差很多,以下列出幾點。

Function overload

1
2
3
4
void Dosomething(int v);
void Dosomething(float v);
Dosomething(1);
Dosomething(3.14f);

這樣的Code在C++可行,在C會編譯失敗,因此要自行加上suffix錯開

1
2
3
4
void DosomethingWithInt(int v);
void DosomethingWithFloat(float v);
DosomethingWithInt(1);
DosomethingWithFloat(3.14f);

雖然效果是一樣的,不過人的記憶力是有限的,同時兩個淚名稱不同,功能相似的函式,有事沒事要分心注意,會殺死一堆腦細胞。
在C11之後,終於有了Generic Selections可用了。

1
2
3
4
5
define Dosomething(X) _Generic((X),  \
int: DosomethingWithInt, \
float: DosomethingWithFloat)(X)
Dosomething(1);
Dosomething(3.14f);

這下看起來好多了,不過如果每增加一種寒士,就要修改一次Dosomething的定義。還是很麻煩啊。這也無法解決所有問題。

Constructor & Destructor

在C++當中是

1
2
3
4
5
6
7
8
9
10
struct Obj {
Obj(int v);
~Obj();
};
int Doanotherthing(Obj *v);
nt Dosomething()
{
Obj local(10);
return Doanotherthing(&local);
}

同樣的Code在C與研究寫得支離破碎了

1
2
3
4
5
6
7
8
9
10
void init_Obj(Obj *this, int v) 
void uninit_Obj(Obj *this);
int Dosomething()
{
Obj local;
init_Obj(&local, 10);
int result = Doanotherthing(&local);
uninit_Obj(&local);
return result;
}

由於C不會主動去呼叫Destructor,因此要將計算的值存起來,所以要主動呼叫Destructor。
由於我們不能簡單的把Constructor和Destructor定義成inituninit就好,原因同上面的Function overload,只好加上自行的suffix避開這個問題。

Member function

雖然這兩樣寫差異無幾

1
2
3
Obj *obj;
obj->Dosomething(); // member function
Dosomething(obj); // pass object to function

萬一有個cstruct 也有Dosomething的函式怎麼辦

1
2
3
Obj2 *obj2;
obj2->Dosomething(); // member function
DosomethingWithObj2(obj2); // pass object to function

又回到老問題了,不能function overload就要手動繞過很多眉角。

又是一個很雜的題目。

Continuation

看了很多定義之後,覺得這定義是最好的。

所謂continuation,其實本來是一個函數調用機制。

我們熟悉的函數調用方法都是使用堆棧,采用Activation record或者叫Stack frame來記錄從最頂層函數到當前函數的所有context。一個frame/record就是一個函數的局部上下文信息,包括所有的局部變量的值和SP, PC指針的值(通過靜態分析,某些局部變量的信息是不必保存的,特殊的如尾調用的情況則不需要任何stack frame。不過,邏輯上,我們認爲所有信息都被保存了)。函數
的調用前往往伴隨著一些push來保存context信息,函數退出時則是取消當前的record/frame,恢複上一個調用者的record/frame。

如果有用過C/C++/Java等開發過,對於Stack Frame隊上面這段話應該不陌生。

Continuation則是另一種函數調用方式。它不采用堆棧來保存上下文,而是把這些信息保存在continuation record中。這些continuation record和堆棧的activation record的區別在於,它不采用後入先出的線性方式,所有record被組成一棵樹(或者圖),從一個函數調用另一個函數就等於給當前節點生成一個子節點,然後把系統寄存器移動到這個子節點。一個函數的退出等於從當前節點退回到父節點。 

這些節點的刪除是由garbage collection來管理。如果沒有引用這個record,則它就是可以被刪除的。 

Read more »

From callback to (Future -> Functor -> Monad) 這篇寫得很好,雖然是用Javascript實做,不過還是值得一看。目前我的能力還不足以使用C++重寫一次,先用殘破的Javascipt來練習吧。

Callback

1
2
3
4
fs.readFile('...', function (err, data) {
if (err) throw err;
....
});

這就是continuation-passing style。最大的問題就是nested callback之後,整個程式碼雜亂無章,難以維護。因此想了很多方法來改善流程。

Future

現在各大語言都有Future跟Promise了,Javascript的版本可以參考上面那篇文章的實做。

這邊是參考How to JIT - an introductionHello, JIT World: The Joy of Simple JITs 的感想。

Sample Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

// Allocates RWX memory of given size and returns a pointer to it. On failure,
// prints out the error and returns NULL.
void* alloc_executable_memory(size_t size) {
void* ptr = mmap(0, size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (ptr == (void*)-1) {
perror("mmap");
return NULL;
}
return ptr;
}

void emit_code_into_memory(unsigned char* m) {
unsigned char code[] = {
0x48, 0x89, 0xf8, // mov %rdi, %rax
0x48, 0x83, 0xc0, 0x04, // add $4, %rax
0xc3 // ret
};
memcpy(m, code, sizeof(code));
}

const size_t SIZE = 1024;
typedef long (*JittedFunc)(long);

// Allocates RWX memory directly.
void run_from_rwx() {
void* m = alloc_executable_memory(SIZE);
emit_code_into_memory(m);

JittedFunc func = m;
int result = func(2);
printf("result = %d\n", result);
}
Read more »

雖然原來名稱叫10 C99 tricks,不過有些跟C99沒關係,不過還是有參考價值。

Ternary operator without middle operand (gnu extension)

1
2
3
4
5
// Instead of
x = x ? x : 10;

// We can use the shorter form:
x = x ?: 10;

個人覺得, 這個樣子更不容易看出程式在寫什麼

Unamed struct for compound type

根據實驗之後,這也不需要C99,C89就能正常運作了
在一般的情形之下,這樣子Compilier會提出警告

1
2
3
struct {
float x, y, z;
};

Clang發出這樣的警告

1
2
3
4
demo.c:5:1: warning: declaration does not declare anything [-Wmissing-declarations]
struct {
^~~~~~
1 warning generated.

但是如果再union / struct當中這樣使用的話就沒有問題,可以依照自己喜歡的方式使用

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef union {
struct { float x, y, z; };
struct { vec2_t xy; };
struct { float x_; vec2_t yz; };
float v[3];
} vec3_t;
#define VEC3(x, y, z) { {x, y, z} }

vec3_t vec = VEC3(1, 2, 3);
// We can access the attributes in different ways.
float x = vec.x;
vec2_t xy = vec.xy;
float z = vec.v[2];

IS_DEFINED macro

無法理解為什麼要設計的這麼複雜..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// As used in the linux kernel.
// A macro that expands to 1 if a preprocessor value
// was defined to 1, and 0 if it was not defined or
// defined to an other value.

#define IS_DEFINED(macro) IS_DEFINED_(macro)
#define MACROTEST_1 ,
#define IS_DEFINED_(value) IS_DEFINED__(MACROTEST_##value)
#define IS_DEFINED__(comma) IS_DEFINED___(comma 1, 0)
#define IS_DEFINED___(_, v, ...) v

// Can be used in preprocessor macros:
#if IS_DEFINED(SOMETHING)
...
#endif

// Or even directly in the code.
// Same effect but looks better.
if (IS_DEFINED(SOMETHING)) {
...
}

Convenience macro for Debuging

其實這個方法不限於OpenGL,像GetLastErrorerrno都可以用類似的方法來確認狀態。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Not really special, but so useful I thought
// I'll put it here. Can also be used with other
// libraries (OpenAL, OpenSLES, ...)
#ifdef DEBUG
# define GL(line) do { \
line; \
assert(glGetError() == GL_NO_ERROR); \
} while(0)
#else
# define GL(line) line
#endif

// Put GL around all your opengl calls:
GL(glClear(GL_COLORS_MASK));
GL(pos_loc = glGetAttribLocation(prog, "pos"));

Array size macro

這個也不世新玩意了

1
2
3
4
5
6
7
8
9
10
11
// Is there any C project that does not use it?
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

// Can be used like this:
int a[] = {0, 4, 5, 6};
int n = ARRAY_SIZE(a); // n = 4

// Warning: does not work with array arguments to functions:
int func(int a[]) {
int nb = ARRAY_SIZE(a); // Would not work!
}

Safe-type macro (uses a gnu extension)

當然這也不是只用於min, max, 還可以用於swap等…弱化版的Template。

1
2
3
4
5
#define min(a, b) ({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; \
})

Passing pointer to unnamed variables to function.

這是一般的寫法

1
2
3
4
void func(const int *arg);
// Instead of using a local variable.
int tmp[] = {10, 20, 30};
func(tmp);

不過可以寫成這樣

1
2
// We can write.
func( (const int[]){10, 20, 30} );

更進一步

1
2
3
// Can be useful with a helper macro.
#define VEC(...) ((const int[]){__VA_ARGS__})
func(VEC(10, 20, 30));

如果搭配上designated initializers威力更大

1
2
3
4
5
6
typedef struct {
float x, y;
} vec2_t;
void func(const vec2_t *arg);
#define make_struct(T, ...) (&(const T){ __VA_ARGS__})
func(make_struct(vec2_t, .y = 9999, .x = 20));

Named initializer, with default values

designated initializers跟Variadic Macros的組合技

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// I use this one all the time when writing
// video game. One of the reason why I
// don't like to use C++.

// Let say we have this struct
struct obj {
const char *name;
float pos[2];
float color[4];
};

// We can write a macro like this one
#define OBJ(_name, ...) \
(struct obj) { \
.name = _name, \
.color = {1, 1, 1, 1}, \
__VA_ARGS__ \
};

// Now we can use the macro to create new objects.
// This one with color defaulted to {1, 1, 1, 1}.
struct obj o1 = OBJ("o1", .pos = {0, 10});
// This one with pos defaulted to {0, 0}.
struct obj o2 = OBJ("o2", .color = {1, 0, 0, 1});

X macros

即使在C++當中,這也是個非常重要的技巧之一,利用Macro來進行Code Generation。
X Macro分成兩部分,一個是彼此相相關連的List,另外一個是巨集,對這個List進行展開動作,而這點Template無能為力。
例如

1
2
3
4
5
6
7
8
9
10
11
#define COLORS \
X(Cred, "red") \
X(Cblue, "blue") \
X(Cgreen, "green")

#define X(a, b) a,
enum Color { COLORS };
#undef X
#define X(a, b) b,
static char *ColorStrings[] = { COLORS };
#undef X

當要新增一種顏色的時候,只需要在COLORS那邊修改,減少了維護和犯錯的可能性。
如果需要更進一步的學習,可以參考

  • X Macro
  • The X Macro
  • The New C: X Macros
  • Reduce C-language coding errors with X macros Part 1 Part 2 Part 3
  • Real-world use of X-Macros

    State machine helper using LINE

    Generator的簡易實現,將S__LINE__來當做State之一。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    // This is a great trick.
    // Instead of:

    int iter(int state) {
    switch (state) {
    case 0:
    printf("step 0\n");
    return 1;
    case 1:
    printf("step 1\n");
    return 2;
    case 2:
    printf("step 2\n");
    return 3;
    case 3:
    return -1;
    }
    }

    // We can define:
    #define START switch(state) { case 0:
    #define END return -1; }
    #define YIELD return __LINE__; case __LINE__:;

    // And now the function can be written
    int iter(int state) {
    START
    printf("step 0\n");
    YIELD
    printf("step 1\n");
    YIELD
    printf("step 2\n");
    END
    }

前情提要

長久以來寫C/C++的Code時,配置環境是很麻煩的一件事,通常會遇到以下的事情

  • 下載第三方Library
  • 設定Include Path
  • 設定Linking library
  • Cross Platform的設置
  • Makefile的編寫

雖然有了CMake幫助解決塊平台的問題。不過還是不夠。有時我們想要Rust的Cargo或是Go Build這樣的東西,而Biicode給了我們一點光明。

Read more »

這篇是How to get started with the LLVM C API的讀後感,不過用我自己的方式表達。

先講結論

我重寫了程式碼,放在整篇文章的最後面,先看輸出結果。再回頭看程式碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
$ cc `llvm-config --cflags` -c sum.c
$ c++ `llvm-config --cxxflags --ldflags --libs core executionengine jit interpreter analysis native bitwriter --system-libs` sum.o -o sum
$ ./sum 42 99
141
$ llvm-dis sum.bc
$ cat sum.ll
; ModuleID = 'sum.bc'

define i32 @sum(i32, i32) {
entry:
%tmp = add i32 %0, %1
ret i32 %tmp
}

這邊可以看兩個部份, Bitcode內容,以及JIT技術。之前介紹過LLVM的Bitcode,利用LLVM API可以生成Bitcode

建立Module

這邊就不特別提了,原來的連結寫得比較清楚。

1
LLVMModuleRef mod = LLVMModuleCreateWithName("my_module");
Read more »

看到這篇Type safe handles in C++覺得很有意思。原來可以這樣用。兩個同樣type,不過代表不同意義的Handle,要怎麼區別才安全。

Tag solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
template<class Tag, class impl, impl default_value>
class ID
{
public:
static ID invalid() { return ID(); }

// Defaults to ID::invalid()
ID() : m_val(default_value) { }

// Explicit constructor:
explicit ID(impl val) : m_val(val) { }

// Explicit conversion to get back the impl:
explicit operator impl() const { return m_val; }

friend bool operator==(ID a, ID b) { return a.m_val == b.m_val; }
friend bool operator!=(ID a, ID b) { return a.m_val != b.m_val; }

private:
impl m_val;
};
struct sound_tag{};
typedef ID<sound_tag, int, -1> sound_id;
struct sprite_tag{};
typedef ID<sprite_tag, int, -1> sprite_id;

Strong typedef

根據未來的C++ Proposal Toward Opaque Typedefs for C++1Y,用Boost_StrongTypedef可以達到類似的效果

1
2
3
4
5
#include <boost/serialization/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(int, sound_id);
BOOST_STRONG_TYPEDEF(int, sprite_id);
sprite_id gfx = create_sprite();
destroy_sound(gfx); // ERRROR!

其實是看了The C++ Memory Model之後,對於之前懵懂的點有點茅塞頓開,寫下來記錄。

Pre-C/C++11

先來看以下這段Code

1
2
3
4
5
6
7
8
9
10
11
12
int count = 0;
bool flag = false;
void thread1()
{
count = 1; // (1)
flag = true; // (2)
}
void thread2()
{
while(!flag);
r0 = count;
}

就直覺上來說,r0拿到的值會是1,而事實往往不會這麼簡單。Compiler有可能把(1)和(2)的指令重排,因為對Single thread來說,如此重排不匯兌結果產生任何影響,如果我們就算強迫Compiler禁止指令重排,CPU也會有機會做這件事

Read more »