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