Showing posts with label C Language. Show all posts
Showing posts with label C Language. Show all posts

Saturday, December 27, 2014

Getopt

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;

opterr = 0;
  while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}

Here are some examples showing what this program prints with different combinations of arguments:

% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)

% testopt -c foo
aflag = 0, bflag = 0, cvalue = foo

% testopt -cfoo
aflag = 0, bflag = 0, cvalue = foo

% testopt arg1
aflag = 0, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -a arg1
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -c foo arg1
aflag = 0, bflag = 0, cvalue = foo
Non-option argument arg1

% testopt -a -- -b
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -b

% testopt -a -
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -

An option character in this string can be followed by a colon (‘:’) to indicate that it takes a required argument. If an option character is followed by two colons (‘::’), its argument is optional.


This optarg is set by getopt to point at the value of the option argument, for those options that accept arguments.


 


Reference


[1] http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html


[2] http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html


[3] http://en.wikipedia.org/wiki/Getopt

Sunday, November 30, 2014

Array initialization

Basic initialization
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
other syntax 
int myArray[10] = { [4] = 5, [2] = 5 }; 
is equivalent to
int myArray[6] = { 0, 0, 5, 0, 5, 0 };
initialize a range of elements to the same value
int myArray[10] = {[0 ... 9] = 5};
 
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...

So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0(only for Zero initial)

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
static int myArray[10]; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:
int myArray[10] = {}; // all elements 0 in C++


And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)
Reference
[1] http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c
[2] https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
[3] http://www.lemoda.net/c/array-initialization/ (experiment)






Sunday, November 16, 2014

Inline Functions versus Macros

add my commend into the content

  1. Inline functions follow all the protocols of type safety enforced on normal functions.
    • more safe then the macro, especially, for the type defination.
    • for the type check, macro is checked by prepocessor, and inline functions is checked by compilar.
  2. Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.
    • only difference is keyword “inline”
  3. Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.
    • more variable for arguments
  4. There is no risk if called multiple times. But there is risk in macros which can be dangerous when the argument is an expression.
  5. functions can include multiple lines of code without trailing backlashes.
  6. functions have thier own scope for variables and they can return a value.
  7. debuging

Reference

[1] http://msdn.microsoft.com/en-us/library/bf6bf4cf.aspx

[2] http://www.thegeekstuff.com/2013/04/c-macros-inline-functions/

Friday, November 14, 2014

function and function-like macro

if we use the same name for those things. avoid the prepocessor will expand the function first, we usaully add parenthese to prevent.

simple example

#include <stdio.h>
#define test(x) __test(x)
#define __test(x) printf("\n%d\n", x + 1);

int test(int x);
#undef test

int main()
{
    test(1);
}
int (test)(int x)
{
    printf("\n%d\n", x);
}

Referemce

http://stackoverflow.com/questions/13600790/what-do-the-parentheses-around-a-function-name-mean

Thursday, November 6, 2014

In C, Keyword “static”

 
#include <stdio.h>

int global_var; //statically allocated as a global variable
static int static_var; //statically allocated but only accessible within file

void my_function(void){
static int my_static = 0; //statically allocated, accessible within my_function
int my_stack = 0; //allocated on the stack

printf("my_static:%d, my_stack:%d\n", my_static, my_stack);
my_stack++;
my_static++;
}
Answer: 

my_static:0, my_stack:0
my_static:1, my_stack:0
my_static:2, my_stack:0
my_static:3, my_stack:0
my_static:4, my_stack:0
Reference
[1] http://coactionos.com/embedded%20design%20tips/2013/10/18/Tips-RAM-Flash-Usage-in-Embedded-C-Programs/

RAM/Flash Usage in Embedded C Programs

 

Read-only memory(Flash)

Data Section

int data_variable = 500;

Read-only date



constant

const int read_only_variable = 2000;

Text(code)



“literal pool” may in the function.


void my_function(void){
int x;
x = 200;
printf("X is %d\n", x);
}

Read-Write Data(RAM)


Data section


int data_var = 500; //require flash memory to stored.

BSS section


int bss_var0;
int bss_var1 = 0;
//doesn’t need require flash memory to stored.

Heap section


static int static_var;
buffer = malloc(512);

Stack section


int my_function(int a, int b, int c, int d)

Reference


[1] http://coactionos.com/embedded%20design%20tips/2013/10/18/Tips-RAM-Flash-Usage-in-Embedded-C-Programs/

Sunday, October 26, 2014

Declarations

C 99 provide programmer a way to save a memory space.

struct DM {

int x,

char* z[]

}

z just a label, compilar won’t allocate a memory for that, and this declaration only could put in last of structure declaration. therefore if we need to allocate a space for this structure when we need to store a data in variable z, otherwise we will assign wrong address which is next to variable x.

 

Reference

[1] C in a nutshell

Thursday, May 9, 2013

State Machine ? Function Point !!!

不管中文或是英文都有很多文章在介紹這兩個理論的概念,在這裡是想用這兩種概念將程式寫的更容易維護和設計。

State Machine(SM)第一次看到這個名詞是我在研讀HMM的時後(有機會將這有趣的數學分享給大家),簡單來說就是狀態之間的轉移,數學上是以"機率"作為轉移依據,而在程式上是以"條件式"來決定。條件式在C語言裡不外乎使用 if / switch,

先來簡單的狀態序列<2>,配上常見的寫法我想會是~~

image

if (S=1) S = 2; do event S1

elseif (S=2) x = 3; do evnet S2

elseif (S=3) do event S3

或是用switch case…,想要讓狀態機多活一下,很直覺得就給它加個do while。這樣就大功告成了!?

小小狀態機或許這樣應該足夠了,但現在隨著硬體技術隨著<1>Moore定律的規範下不斷進步,其實軟體這裡也不會閒著,狀態機也是龐大的可怕,那這樣的寫法好maintain嗎? 我想這部分可以等到各位在工作時可以驗證一下,這裡是討論程式概念。

要怎麼做才直接且容易維護呢? 首先我們仔細想想,上述概念的寫法應該是這樣的SM。

image

首先,我想引用<3><4>來解釋SM table的設計,這方法可以用來紀錄下一個狀態位置。

CurrentState = SMTable[CurrentState ] ;

很好,有了這個機制我們的架構就變成這樣了!

image

這是俗稱的多此一舉,脫褲子放屁? 問題出在哪呢? 因為每個狀態有屬於自己的函式要處理,如果能跟著CurrentState這index改變,那就兩全其美了。所以就有function point<5-7>存在的必要性。

此外,要寫好貼切的function point,我想宣告的問題可是非常重要,如#define, typedef, 宣告型態<8>...

這是我簡單寫一個上面所形容的狀態機(source code)分享給各位,希望能讓各位產生一絲絲的共鳴。

<Reference>

<1>http://en.wikipedia.org/wiki/Moore's_law

<2>http://www.swarthmore.edu/NatSci/echeeve1/Class/e15/E15Lab2/CStateMachines/CStateMachines.html

<3>http://www.conman.org/projects/essays/states.html

<4>http://johnsantic.com/comp/state.html

<5>http://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c-examples-hints-and-tips-ple

<6>http://stackoverflow.com/questions/133214/is-there-a-typical-state-machine-implementation-pattern

<7>http://www.newty.de/fpt/intro.html#what

<8>http://www.devx.com/tips/Tip/13829

Register Transfer Level Design with Verilog (1) [ebook]

設計程式之所以有趣不外乎是它的千變萬化,同樣的結果卻有不同的寫法。 但這些不同寫法當中也並沒有分誰對誰錯,也沒有制定標準來規範何事該用何解。 這也就是我們設計者的珍貴!! [1] Primitive Instantiations 在Verilog中最基本的邏輯...