2009年7月7日 星期二

取得LINUX系統記憶體剩餘空間

在linux下,沒用到的記憶體空間會被拿來當作buffer/cache使用,

以加速I/O存取

所以會感覺記憶體占用很多,

其實實際上如果程式需要記憶體,

就會釋放buffer/cache的空間,所以通常記憶體幾乎都是保持在很高的使用量。



使用free指令,

"-/+ buffers/cache"那一行的free就是實際上系統剩下來沒被其他程式吃掉的記憶體大小


可以用以下的指令取得真實的剩餘空間
echo -n free memory:;free -m | grep buffers/cache | awk '{print $4}'

2009年7月6日 星期一

C陣列與指標

宣告陣列時,
無論是幾維的陣列,
C語言都以分配一塊連續的記憶體空間來處理。


所以這種時候,可以把它當一維陣列處理

C以row為主,假設是二維陣列 arr[2][2]
當一維時的順序就是:
arr[0][0] arr[0][1] arr[1][0] arr[1][1]




雖然指標和陣列用起來差不多,
不過實際上意義是不太一樣的,
可以參考
http://dascan.pixnet.net/blog/post/15600458
http://squall.cs.ntou.edu.tw/cprog/Materials/AdvancedArray.html





要宣告一個指標代表陣列,要用以下的方法:

int data[5][5][5][5];
int (*p)[5][5][5];

可以參考
http://blog.udn.com/cchahacaptain/2197712

2009年7月2日 星期四

混合C與C++的程式

參考這個網站的:
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html

在c++的程式內,使用C++標準函式庫,需要標明namespace:
#include <>; //cstdio

int main(){
...
std::printf(...);
...
}

在c++的程式內,使用C標準函式庫,用法跟c一樣:
#include <> //stdio.h

int main(){
...
printf(...);
...
}

在c++的程式內,使用C函式庫:
extern "C" {
#include "" //my-header.h
}

int main(){
...
my_func(...);
...
}


若要同一個header file給c與c++直接使用,也可以在header內加上exter "C",並判斷目前是c或c++使用

------------------------------
//my-header.h
#ifdef __cplusplus
extern "C" {
#endif

my-function(...);

#ifdef __cplusplus
}
#endif

------------------------------
//main.cpp

#include "" //my-header.h

int main(){
...
my_func(...);
...
}
------------------------------

若不想要include my-header.h,只要使用某幾個c function,可以直接宣告完整的prototype
//main.cpp
extern "C" my_func(int a, int b, int c);
or
//main.cpp
extern "C" {
my_func1(int a, int b, int c);
my_func2(int a, int b, int c);
my_func3(int a, int b, int c);
}
用到時直接用
//main.cpp
my_func1(...);

若要讓c程式call到c的某個function, 使用extern "C"可以使complier將此function給linker的資訊使用c的格式

//my.cpp
extern "C" my_cpp_func(int a, int b);

my_cpp_func(int a, int b){
...
}