2014年8月14日 星期四

even-odd register pair




在32bits 的機器中, 要如何表示64 bit 長度的資料?
ex: long long, unsigned long long, double
有一種方式是用一對32bit register pair 來表示, 稱為even-odd register pair

例如:
unsigned long long ull_input = 0x1122334455667788ULL;

如果有某個指令可以做上下半部交換 稱為swap
則指令可能長成這樣 swap r0
(並不用再指定r1)


但在inline assembly 中使用到register pair
可能會讓你有點混淆

unsigned long long
swap (unsigned long long i1, unsigned i2)
{
  unsigned long long i1_return_value;

  __asm__ ("swap\t%0, %2"
          : "=r" (i1_return_value)
          : "0" (i1), "r" (i2)
          );

  return i1_return_value;
}


首先是i1 是unsigned long long 但是卻只指定給一個register
我一開始很想問 那另外一半是怎麼傳的,
看來應該是compiler 會幫你處理 因為你的i1 明白告知型別是unsigned long long
而回傳 看起來則是把一個register 傳給unsigned long long (只傳了一半)
但其實是整個even-odd 都傳回了。

再考慮endian 
(把even-odd 看成是memory, 前者代表address 小)

big endian ->  unsigned long long 是 even-odd
(把MSB 放到位址小的地方)
little endian ->  unsigned long long 是 odd-even
(把LSB 放到位址小的地方)

所以排起來都是EVEN-ODD   (前者代表address 小)

2014年8月10日 星期日

pointer vs reference



const int * p;  // p is a pointer to const int
int * const p; // p is a const pointer to int
const int * const p; // p is a const pointer to const int

int &r; // r is a const reference to int
(特別注意: 如果你重新assign r, compiler 並不會complaint)
const int &r; // r is a const reference to const int

2014年8月9日 星期六

你不用知道多型中實際的類別是什麼 讓多型的物件自己告訴你 他是誰


前提:
有一個Base class Vehicle
其Subclass Car, Trunk, Helicopter
有一個Container 內型別是Vehicle (但實體是subclass)
今天要對container 內的元素做排序, 兩兩比較
我要如何知道該元素究竟是哪個subclass ?

作法一:
3種類別 兩兩比較, 共有9種可能性
用dynamic_cast 做9個if else.

這個方法是OK的, 但code 看起來會比較髒亂
因為如果是4種類別 會達到16個if else,
更別說如果有10種類別了.

作法二:
讓他自己告訴你他是誰,
例如你想在知道他實際的類別之後 給予priority
則可以在base class 宣告pure virtual function : getPriority
讓子類別分別實作 回傳其priority
這樣一來你只要呼叫getPriority
原本要呼叫9次的if else
只要別成  呼叫兩個getPriority + 一次比較.
瞬間就讓程式碼優美許多

2014年7月18日 星期五

vim 顯示行尾空白, 與tab 字元


良好的 coding style 是不允許行尾空白的儘管事後有很多方式可以自動刪除掉但如果可以在編輯的時候就看到行尾空白 也是很不錯的在.vimrc 貼上下列語法即可" High light unwanted spaces in end of linehighlight ExtraWhitespace ctermbg=darkred guibg=darkcyanautocmd BufEnter * if &ft != 'help' | match ExtraWhitespace /\s\+$/ | endifautocmd BufEnter * if &ft == 'help' | match none /\s\+$/ | endif


另一條良好的coding stype
則是用space 取代tab (因為tab 是不固定的字元數目, 容易造成混亂)
但Makefile 又必須使用tab 而不是space
所以還是有顯示tab 的必要

set listchars=tab:>>
set list



2014年6月22日 星期日

LLVM tablegen multiclass definitions and instances


tablegen 的目的是為了提出records 中,所共有的部分。
所以許多語言特色都是用來簡化,

例如: class template arguments

以下面這個例子來說
def bork {      // Value
  bit isMod = 1;
  bit isRef = 0;
}
def hork {      // Value
  bit isMod = 1;
  bit isRef = 1;
}
def zork {      // Value
  bit isMod = 0;
  bit isRef = 1;
}



可以改寫成


class ModRefValue< bit<2>  value >{
bit<2> Value = value
}

class Value<ModRefValue MR> {
bit isMod = MR.Value{0}
bit isRef = MR.Value{0}
}

def bork : Value<Mod>
def hork : Value<ModRef>
def zork : Value<Ref>


看起來簡化多了。
class template arguments 是用來簡化class 內部的value
接下來介紹multiclass definition and instances
可以用來簡化class instance


def ADD_rr : rrinst<0b111, "add">;
def ADD_ri : riinst<0b111, "add">;
def SUB_rr : rrinst<0b101, "sub">;
def SUB_ri : riinst<0b101, "sub">;
def MUL_rr : rrinst<0b100, "mul">;
def MUL_ri : riinst<0b100, "mul">;


很多指令都有_rr, _ri 這兩種版本,
能不能再class instantiation 的時候只宣告一次add, sub, mul 就好
能可以自動定義出add_rr, add_ri 這兩種版本,
這時候就要用multiclass 跟defm

defm ADD : ri_insn<0b111, "add">
defm SUB : ri_insn<0b101, "sub">
defm MUL : ri_insn<0b100, "mul">

multiclass ri_insn < > {

def _rr
def _ri

}
(產生出來的def 會做string concatenation)

而且defm 不只可以放在外面,也可以放在multiclass裡面
參考 http://llvm.org/docs/TableGen/LangIntro.html


2014年6月17日 星期二

用python 來取代shell script


最近工作上,原本有個程式是用shell script 寫的,目的也就是一些簡單的整合應用
但後來越寫越大, 覺得程式碼好醜( shell language 真是我看過最醜的語言)
索性把整個shell script 改寫成python

原本就預期改寫之後的程式碼會比較清晰 而且更短
結果果然是這樣, 驗證了python 真的能夠快速開發的設計理念

但人還是不滿足
python 最強大的library 也成了最大的問題
這麼多module, function name, 怎麼記得住阿?

救星很可能就是ipython (http://ipython.org/index.html)

2014年6月12日 星期四

Preprocessor # and ##

 

介紹兩個用在macro 的運算子

## : 把macro 裡的參數,跟其他string 串接起來

# : 把macro 裡的參數,當作string

#define w(n) "imm"#n
#define w2(n) imm##n

int main()
{
  int imm5 = 10;
  printf("%s\n", w(10));
  printf("%d\n", w2(5));
  return 0;
}

第一個printf 我想要一個string 當參數 所以用#

第二個printf 我想要一個變數 所以用##

 

Reference

https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

2014年6月11日 星期三

Build LLVM with cmake

 

cmake 可以產生不同的build file (ex: unix makefile)

cmake –help
最後面會列出在你平台環境上可以產生的makefile 種類

cmake –G “Unix Makefiles”
指令產生"Unix Makefiles”
如果不指定,也會自動偵測。

所以build LLVM 最簡單的命令就是在build directory

cmake PATH/TO/LLVM/SRC
make

 

其它variable 請參考
http://llvm.org/docs/CMake.html#options-and-variables

cmake -DLLVM_TARGETS_TO_BUILD="X86”     # only build x86 target
           -DCMAKE_INSTALL_PREFIX="$PWD/../install"   # specify installation path
           ../llvm-3.4.1.src/   

Newlib syscall


在porting Newlib for a new architecture 要注意事項,第六點
  1. Add a platform subdirectory to libgloss You need to add a bsp for your platform. This is the minimum set of syscalls needed by newlib and any linker scripts needed. This varies from board to board (it can also be a simulator). See the mn10300 or fr30 for examples. You will need to edit configure.in and regenerate configure so it will build your new files. By default you get libnosys which gives you a set of default syscall stubs. The majority of the stubs just return failure. You still need to supply an __exit routine. This can be as simple as generating an exception to stop the program.
意思是說要在libgross 下新增一個architecture directory
並且實作必要提供的最少syscall
以read system call 來說,_read_r 會需要底層平台支援(呼叫_read),
所以必須提供所謂BSP 也就是libgross,內含處理這些system call的實作。
reent/readr.c
_ssize_t
_DEFUN (_read_r, (ptr, fd, buf, cnt),
     struct _reent *ptr _AND
     int fd _AND
     _PTR buf _AND
     size_t cnt)
{
  _ssize_t ret;
  errno = 0;
  if ((ret = (_ssize_t)_read (fd, buf, cnt)) == -1 && errno != 0)
    ptr->_errno = errno;
  return ret;
}
libgloss/fr30/syscalls.c
int
_read (file, ptr, len)
     int    file;
     char * ptr;
     int    len;
{
  asm ("ldi:8 %0, r0" :: "i" (SYS_read) : "r0");
  asm ("int   #10");
  return;
}

僅是發system call,讓Vector Table 內的system call handler 去處理。



2014年6月10日 星期二

Newlib reentrancy


引用Newlib 的原文
Reentrancy is a characteristic of library functions which allows multiple processes to use the same address space with assurance that the values stored in those spaces will remain constant between calls.
意思是說,當某process A 執行function到一半的時候, 允許其他processes B 去執行,並且可以確保B執行完畢之後,A 還可以正確的執行剩下的指令。
一開始我對這個reentrancy 的定義很confused,原因是我記得reentrancy 跟thread-safe 是兩件事,可參考 Wiki Reentrancy ,reentrancy 是在談single process 環境下,user code 與ISR的關係 (這並不是multithread)。
但Newlib 很顯然是把reentrancy 跟multithreading  扯在一起了。為了繼續看下去,只好先接受它的定義囉。
為什麼library function 要reentrant ?
最簡單的例子是errno
每個thread 都應該維護自己的errno,不可以影響其他thread 的執行。

所以Newlib 維護了一個reentrancy structure  struct _reent,內含所有會被library 修改到的global variables。errno 當然是其中一個member,而且還是第一個。(因為它太常被修改到了)
而user 使用到的errno 其實並不是變數,而是macro
這個macro 會替換成_reent 內的errno。

再繼續看下去之前,先談談
其實Newlib 也提供不需要reentrancy 的版本。
而這些版本的code 只要共同存取一個global reentrancy structure 就好了
(根本就不需要reentrant 了,還要去集中管理,這設計很奇怪)
newlib/libc/include/sys/errno.h
#ifndef _REENT_ONLY
#define errno (*__errno())
extern int *__errno _PARAMS ((void));
#endif

newlib/libc/errno/errno.c
int *
__errno ()
{
  return &_REENT->_errno;
}
newlib/libc/include/sys/reent.h
#if defined(__DYNAMIC_REENT__) && !defined(__SINGLE_THREAD__)
#ifndef __getreent
  struct _reent * _EXFUN(__getreent, (void));
#endif
# define _REENT (__getreent())
#else /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
# define _REENT _impure_ptr#endif /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
newlib/libc/reent/impure.c
static struct _reent __ATTRIBUTE_IMPURE_DATA__ impure_data = _REENT_INIT (impure_data);
struct _reent *__ATTRIBUTE_IMPURE_PTR__ _impure_ptr = &impure_data;
所以得到 _REENT 是指到global reentrancy structure 的指標。
(不需要reentrancy 的code 都可以使用_REENT)
但NEWLIB 同時也提供了要reentrant 的版本
通常這些function 都是prependding ‘_’ 跟pendding ‘_r"’
例如: fopen

FILE *
_DEFUN(_fopen_r, (ptr, file, mode),
       struct _reent *ptr _AND
       _CONST char *__restrict file _AND
       _CONST char *__restrict mode)
{
…
}
#ifndef _REENT_ONLY
FILE *
_DEFUN(fopen, (file, mode),
       _CONST char *file _AND
       _CONST char *mode)
{
  return _fopen_r (_REENT, file, mode);
}
#endif

fopen 是non-reentrant 的版本 ,所以它使用global _REENT
_fopen_r 是reentrant 的版本,ptr是用來接收自己的unique _reent
所以如果_fopen_r 要設定errno,只要使用ptr->_errno 就可以改到自己的unique _reent 囉








gcc preprocessor build-in macros

 
GCC preprocessor 定義了許多macro 可以用來幫助程式員,
要怎樣看看這些macro ?
echo "" | cpp -E –dM
這邊舉幾個例子來看看這些macro 可以幫助我們什麼?
1. 想知道你的機器是X86_64 還是I386 ?
#include <stdio.h>
int main() {
#if defined(__x86_64__)
        printf("hello x86_64\n");
#elif defined(__i386__)
        printf("hello i386\n");
#endif
  return 0;
}
2. 想知道你機器上的integer pointer  type 是定義成什麼?
在x86_64
~/tmp $ echo "" | cpp -E -dM | grep __INTPTR_TYPE__
#define __INTPTR_TYPE__ long int
在i386
~/tmp $ echo "" | cpp -E -dM | grep __INTPTR_TYPE__
#define __INTPTR_TYPE__ int










composite data type – its alignment and size


* array

alignment - 等同於元素的alignment
size - 元素size * 元素個數
example:
int array[10];
alignment – 4bytes
size – 4 * 10 bytes

* aggregate (struct)

alignment - 元素中最大的alignment
size – alignment 的最小倍數,並且足以容納所有元素
example:
struct {
char c;
int i;
};
alignment – 4 bytes
size – 8 bytes

* union

alignment - 元素中最大的alignment
size – alignment 的最小倍數,並且足以容納最大size的元素。
union {
char c;
int i;
};
alignment – 4 bytes;
size -  4 bytes

packed variable attribute

#include <stdio.h>
struct data {
        int i;
        char c[3];
        int i2;
}mydata;
struct data1 {
        int i;
        char c[3];
        int i2;
} __attribute__((packed)) mydata1;
enum number {
        n1,
        n2,
        n3,
} number;
enum number1 {
        n11,
        n12,
        n13,
} __attribute__((packed)) number1;
 
int main()
{
  printf ("size of mydata is %lu\n", sizeof (mydata));
  printf ("%p\n", &mydata.i);
  printf ("%p\n", &mydata.c);
  printf ("%p\n", &mydata.i2);
  printf ("size of mydata1 is %lu\n", sizeof (mydata1));
  printf ("%p\n", &mydata1.i);
  printf ("%p\n", &mydata1.c);
  printf ("%p\n", &mydata1.i2);
  printf ("size of number is %lu\n", sizeof (number));
  printf ("size of number1 is %lu\n", sizeof (number1));
  return 0;
}
===================================
size of mydata is 12
300df4
300df8
300dfc
size of mydata1 is 11
300de8
300dec
300def
size of number is 4
size of number1 is 1

====================================
packed 這個variable attribute 可以套用在struct、union、enum。
目的是讓這些結構使用最少的記憶體,
例如:
mydata, compiler 為了performance 通常會對齊資料,所以i2 被強制對齊到4bytes align (儘管c 只用了3byte)
但加了packed 的mydata1,就不管i2 要4bytes align的要求了。
同樣地,用到enum, 會用最小的integral type 來做enumation。
原本是用int (4bytes),改成最小的byte了









2014年6月8日 星期日

human-like robot called Pepper

http://www.taiwannews.com.tw/etn/news_content.php?id=2498393


Guo said that he was honor to be part of such a momentous initiative.

momentous 重要的
initiative 首創精神

The initiative of the work was done by our chief engineer.


http://www.bbc.com/news/technology-27709828

The overall estimate is worth about XXX.

The next big thing



http://www.taiwannews.com.tw/etn/news_content.php?id=2499767


Computex, Taipei 2014, is the second largest computer trade show.
This year, it drew a record number of international buyers and visitors, that's one percent more than the last year's show did according the International External Trade Council.  (國際外貿協會). Of 166 countries and regions, the strongest ones are from China and US.

The executive vice president mark this the end of the show at a press conference.



during its five-day run.
-> during its five-day period. 
run 有經營的意思
A well-run company 經營良好的公司

The largest increase was seen among XXX, OOO, and ZZZ with XXX percent, OOO percent, and ZZZ percent respectively.

The number of China buyers also showed strong annual growth of XX percent,
making China the largest single source of buyers at this year's computex.

The trade show is expected to have generated over US$25 billion in business
-> The trade show is expected to generate over US$25 billion in business.
the same as the exhibition in 2013
-> as much as the exhibition in 2013
representing 22 percent of Taiwan's annual amount in Information and Communication technology export. 

The amount of trade in 34th computex represents 22 percent of Taiwan's annual amount of export in Information and Communication. 

He is quite confident after seeing these good result, attributing the good result to economic recovery in US. and Europe.
attribute 把...歸咎(因)於
I attribute my good performance to my strict discipline. 
我的表現歸因於嚴格的紀律
It's improper to attribute the failure to others. 
把失敗歸因於別人

attribute 認為是某人所有
to attribute the weakness to women. 
把軟弱認為是女人所應有的

wearable devices and Internet of thing (IOT) is the trend of future technology,
Can I find out the future start from stock market? 

2014年6月4日 星期三

GCC – always_inline attribute


下面這個例子,gcc 會warning
hello.c: In function 'api':
hello.c:4:5: warning: asm operand 0 probably doesn't match constraints [enabled by default]
     __asm__ ("add\t%0"
     ^
hello.c:4:5: error: impossible constraint in 'asm'


static inline void api (const unsigned data)
{
    __asm__ ("add\t%0"
            :
            : "i" (data)
            );
}
int main()
{
  const unsigned i = 10;
  api(1);
  return 0;
}

錯誤的原因是 api 內要求data 必須是integer “I”
但是data 一定是常數? 它也有可能是變數,就像main 中傳了i 給api
所以就有可能不滿足限制。
那把api(i) 改成 api(10); 可以嗎?
還是不行 因為其他user 還是可以用api(i)這種寫法
解決方法:
1. 讓gcc 做優化
gcc –O1
這樣 const unsigned data 就真的會變成 integer 而不是變數
2. always_inline

always_inline
Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified. inline function 原本只是建議,但加了always_inline 即使是在O0 的情況下,
這個function 還是會被inline 到main 去,所以const unsigned data 會被拿掉,
直接用1 取代data。
但這樣做怪怪的,如果把程式換成
int main()
{
  const unsigned i = 10;
  api(i);   // 用variable i
  return 0;
}
always_inline 也不行了
為什麼? 看起來是在O0 情況下,並沒有辦法把i 取代成10

下面 網頁列出 –O –O1 情況下,有打開的optimization,可以試試看到底是那些optimizations 才可以。

https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

GCC – function/variable attribute

 

Reference:

Declaring Attributes of Functions

 

Specifying Attributes of Variables

2014年6月2日 星期一

Choose the right industry while you are looking for a job.


Taipei COMPUTEX: 'A good indication' of tech outlook, says Barclays

http://www.taiwannews.com.tw/etn/news_content.php?id=2495539


------------------------------------------------------------------------------------------------------------------------------
This article talks about the computex exhibition 2014.
Two major PC maker ASUS and ACER will show their latest product, including wearable product and new low-cost smartphone.
ASUS will unveil their new transformer tablet with low cost, from the view of a customer, I won't expect their product too much, because the market of smartphone and tablet is becoming more and more competitive and low benefit.
As for ACER, it will exhibit his first wearable watch which can receive text message and be used to monitor user's heart rate.
In my opinion, this product is not an innovation, because Samsung has showed many kind of similar product to market.
The wearable product is a trend, but is still looking for the new application.
(I don't think I would pay for this new watch, but I would like to pay for google glasses)

At the end, HTC, ASUS, and ACER, they are once the leading manufacturer of smartphone, PC,  and Notebook, but they are not any more now due to the lock of innovation. Their profit becomes lower and lower and even worse and worse.
As an indication of looking for job, my advise is "Working and Improving yourself as the time go by, not just reproduce and resolve the bugs".


2014年5月23日 星期五

使用變數型別的良好習慣



最近在把老人寫的code 在x86_64 上做測試
才深刻體會原來寫一個好程式 要注意 data type 的使用


在32bit 機器上
#include <stdio.h>
int main()
{
        int i = 10;
        int *p = &i;
        int pp = (int)p;
        return 0;
}


gcc 不會warning 

但同樣程式在64bit 機器上跑
cast.c:7:20: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
           int pp = (int)p;


這是warning 理論上你可以不用管他
但是這很危險 可能會產生出很多莫名其妙的bug  ~~
所以編譯程式最好加上 -Werror  
把warning 都當成error  處理
迫使你寫的程式沒有額外的風險

回到正題
在64 bit上要解決這個warning or error
要改成

#include <stdio.h>
int main()
{
          int i = 10;
          int *p = &i;
          long pp = (long)p;
          return 0;
}



為什麼?  因為32bit 跟64bit 機器上pointer 長度不同啊
一個是32 bit 一個是64 bit  
所以把64bit 資料強迫轉型成32 bit integer 當然要警告你 可能會lost data 

當然你可以下面這種方式來解決
if machine32
  int pp = (int)p;
elif machine64
 long pp = (long)p;
endif


但這太麻煩了, stdint.h 內定義了 intptr_t 這個type
當你需要把pointer 轉型成 integer 的時候 你不確定是32 or 64bit
就可以使用intptr_t

#include <stdio.h>
#include <stdint.h>
int main()
{
        int i = 10;
        int *p = &i;
        intptr_t pp = (intptr_t)p;
        return 0;
}


所以 下面這三個打印數值是相同的
#include <stdio.h>
#include <stdint.h>
int main()
{
          int i = 10;
          int *p = &i;
          intptr_t pp = (intptr_t)p;
          printf("%p\n", p);
          printf("%lx\n", pp);
          printf("%p\n", &i);
          return 0;
}

 來看看stdint.h 怎樣定義intptr_t

/* Types for `void *' pointers.  */
#if __WORDSIZE == 64
# ifndef __intptr_t_defined
typedef long int                intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned long int       uintptr_t;
#else
# ifndef __intptr_t_defined
typedef int                     intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned int            uintptr_t;
#endif
   

偵測到是64bit 
intptr_t 就是long int  ( 64位元的long int 是64bit, 但32位元的long int是32bit)
否則就是 int   ( 64位元的 int 是32bit, 32位元的int 也是32bit)

================================

同樣的, 關於portability 還有幾點需要介紹
那就是primitive data type
                    32            64
char             1               1
short            2               2
int                4               4
long             4               8
long long     8               8
pointer         4               8

可以注意到 long, and pointer type 是有差異的
所以long 必不portable
所以stdint.h 內也定義了

 35 #ifndef __int8_t_defined
 36 # define __int8_t_defined
 37 typedef signed char             int8_t;
 38 typedef short int               int16_t;
 39 typedef int                     int32_t;
 40 # if __WORDSIZE == 64
 41 typedef long int                int64_t;
 42 # else
 43 __extension__
 44 typedef long long int           int64_t;
 45 # endif
 46 #endif
 47

如果你明確要使用64位元的整數 請使用int64_t
可以看到int64_t 在64bit machine 是long int
而32bit machine 要用long long int

================= size_t =================
看看下面這個小程式

  1 #include <stdio.h>
  2 #include <string.h>
  3
  4 void main()
  5 {
  6         int i = -1;
  7         if (i > strlen ("hello"))
  8                 printf("hello\n");
  9 }

-1 > 5 ?  
yes, 確實會印出hello
這裡的問題是 i 是signed , 用來跟strlen 傳回的size_t (unsigned ) 做比較
會把signed i 轉unsigned 
(unsigned) (-1) 會大於 5

再回來review code
當我們要知道元素大小的時候 我們可以確定至少是0以上
所以應該要用unsigned 來表示
但我們卻常常為了方便而使用int

所以size_t 定義成unsigned integer 
而且是平台相關的
在64bit machine  size_t 是unsigned long
但在32bit machine size_t 是unsigned int


==================ptrdiff_t ================
同樣的 用來表示pointer 之間的difference
但是是signed integer
64bit machine => long
32bit machine => int







2014年5月22日 星期四

sshfs



如果在機器A 上想把機器B的路徑 mount 上來
就用sshfs 吧


Reference:
http://www.cnblogs.com/Anker/p/3438480.html

autotool maintainer mode


最近在更動package autotool, 不曉得為什麼在某些機器上
make 時候會complain : cannot find aclocal-1.14

確實機器上沒有裝aclocal-1.14   (可能有aclocal-1.11)
但回過來想, autotool 不就是要擺脫平台嗎?
為什麼又相依平台上的autotool version?

解法:
在configure.ac 加上 AM_MAINTAINER_MODE([disable])

Reference:
http://www.gnu.org/software/automake/manual/html_node/maintainer_002dmode.html
http://stackoverflow.com/questions/18769770/user-of-autotools-generated-tarball-gets-error-message-aclocal-1-13-command-no

2014年5月19日 星期一

Google Test - 呼叫SetUp/TearDown 在test, test case, and test program level


先複習一些觀念
1.  google test 的架構:
一個test program 內 可含有多個test cases,
而每個test cases 又可內含多個test.

2. 能夠獨立測試除錯的test
對test 來說, 為了維持這個目的, 又要共享一些code
前面我們有提過test fixture 的概念,
讓per-test 可以在執行之前跟執行之後 都可以呼叫SetUp/TearDown

那有沒有per-test-case 的setUp/TearDown ?
那有沒有per-test-program 的setUp/TearDown ?

答案當然是都有 。

Per-test-case:
把你要共享的變數設定成static
並在test fixture 新增
SetUpTestCase
TearDownTestCase
就會在建立第一個test fixture object 呼叫第一個test 之前呼叫SetUpTestCase
並且在摧毀最後一個test fixture object 之後呼叫TearDownTestCase

Per-test-program:
繼承Environment class 並且overwrite Setup/TearDown
並且在呼叫RUN_ALL_TESTS 之前呼叫addGlobalTestEnvironment 註冊該物件

Google Test - Propagating Fatal Failures



Propagating Fatal Failures


如果你讀過primer, 你會知道說
assert_  會產生fatal failure 而停止繼續測試, 但
expect_  會產生non-fatal failure 但不會停止繼續測試.

但這個概念有個陷阱(pitfall) 
其實assert_ failure 時候 只會abort   current function,
但並不會停止其他function 的執行


void foo(int i)
{
  int n = i%2;
  ASSERT_EQ(0, n);
  cout << "won't show if fatal error" << endl;
}

TEST(fooTest, t1) {
  foo(1);
  cout << "will reach here" << endl;
  if (::testing::Test::HasFatalFailure())
        return;
  cout << "won't reach here" << endl;
}

TEST(fooTest, t2) {

  if (::testing::Test::HasFatalFailure())
    return;
  cout << "t2 " << endl;
}


例如上面這個例子, 在test t1 內呼叫foo而產生了fatal failure, 
那foo接下來的code 就不會執行, 但是回到caller 之後是會繼續執行的, 這就是要特別解釋的 fatal 發生而停止執行只在current function.

我們可以呼叫::testing::Test::HasFatalFailure() 去檢查目前test 
是不是有fatal 發生了, 來決定是否繼續執行.

另一個方式是使用
ASSERT_NO_FATAL_FAILURE

TEST(fooTest, t1) {
  ASSERT_NO_FATAL_FAILURE(foo(1));
  cout << "will reach here" << endl;
  if (::testing::Test::HasFatalFailure())
        return;
  cout << "won't reach here" << endl;
}

保證foo(1) 絕對不會產生fatal error,
如果產生了 就不會再繼續執行 

2014年5月18日 星期日

Google Test - 入門


文件: google test primer 
總而言之, google test 號稱有以下這些優點, 就先看看 之後再回來驗證其真實性.

  1. Tests should be independent and repeatable. It’s a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging
    測試與測試之間一定要是獨立而且可以重複的, 如果一個測試的成功或者失敗都還要依賴其他測試的結果, 這樣除錯將會很痛苦. Google Test 藉由每次執行都是執行不同物件來獨立每一個測試. 當一個測試 失敗了, 你可以單獨的重複這個測試.
  2. Tests should be well organized and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base.
    一個Test case 內可以有多個Tests, 並且能把多個Tests 放入fixture class, 使其能共享資料和函數
  3. Tests should be portable and reusable. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux – we are actively working on scripts for other platforms.)
    與平台, 作業系統, 編譯器無關的測試框架.
  4. When tests fail, they should provide as much information about the problem as possible. Google C++ Testing Framework doesn’t stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle.
    如果不是遇到致命的錯誤, 跑一次google test 可以報告出許多錯誤, 不會因為一次錯誤就停此.
  5. The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn’t require the user to enumerate them in order to run them.
  6. Tests should be fast. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other.
    快速測試



A test fixture:
一個test case 可以內含多個test, 這些test 之間往往有些重複的code, 因此fixture 目的是希望可以讓多個test 都去共享一些code, 但又希望每個test 是獨立的.

使用test fixture 必須去宣告一個class derived from testing::Test.



#include "gtest/gtest.h"
class myClass {
public:
  myClass() : init(1) {}
  int get() { return init;}
  void set(int i) { init = i;}
private:
  int init;
};

// To use a test fixture, derive a class from testing::Test.

class myClassTest : public testing::Test {
 protected:  // You should make the members protected s.t. they can be
  virtual void SetUp() {
      
  }

  // Declares the variables your tests want to use.

  myClass mc1;
};

// When you have a test fixture, you define a test using TEST_F

// instead of TEST.
TEST_F(myClassTest, test1) {
  mc1.set(10);
  EXPECT_EQ(10, mc1.get());
}
TEST_F(myClassTest, test2) {
  EXPECT_EQ(1, mc1.get());

}





可以看到一個testCase 內有兩個tests (test1, test2),
如果沒有fixture, 則每個test 都要去宣告myClass, 還有setup function. 現在建立了一個共用的myClassTest來共用code的部分. 
但前面有提到為了保持test 之間的獨立, data 是不共用的.
為了證明這點, 可以看到test1 將init 設成10之後, 在test2 init 還是剛初始化之後的 1.

所以fixture 會

1. 替每個test 配置一份新的fixture class (因此有一份新的資料, 但code 依然是共享的)
2 .呼叫setup
3. teardown




Teaching Google Test How to Print Your Values


當一個test 失敗的時候, google test 會把expect and actual value 給印出來, 方便除錯. 但是google test 只能打印出primitive value, native array, STL container, 其他自訂的type, google test 會打印出bytes (人看不懂的), 所以你可以告訴google test 怎樣打印這個type, 有兩種方式:
1. 替type 實作 << operator
2. 實作printTo function

另外, 要呼叫google test 打印的function 
call ::testing::PrintToString