2013-03-20 27 views
1

我定義在頭文件幾種結構 一些結構都thier恆定值的成員和其他一些結構具有 其成員常量值如何定義在C語言中的頭文件常量變量

零件那些具有常數成員的結構,是否可以在頭文件中定義一個常量變量 ?

像tcp_option.h

struct tcp_opt_nop 
{ 
    _uint_t kind; /* it has a constant value 0x01*/ 
} 

所以想要定義一個常數可變的報頭文件中,像

struct tcp_opt_nop opt_nop={ 0x01}; 

然後這個變量可以由其他源文件使用

+0

你的意思了'define'指令? – squiguy 2013-03-20 17:16:41

+0

你是什麼意思? – user1944267 2013-03-20 17:17:44

+0

你能給一個代碼示例嗎? – interjay 2013-03-20 17:19:02

回答

3

你應該extern你變量。

.h文件:

#ifndef HDR_H 
#define HDR_H 

typedef struct 
{ 
    int kind; /* it has a constant value 0x01*/ 
} tcp_opt_nop; 

extern const tcp_opt_nop opt_nop; 

#endif 

.c文件:

#include "hdr.h" 

const tcp_opt_nop opt_nop = {0x01}; 

主要文件:

#include "hdr.h" 

int main() 
{ 
    printf("%i\n", opt_nop.kind); 
    // ... 
} 
+0

啊,我知道了,你的意思是我需要創建一個'tcp_option.c'文件,只是想知道在編譯時忘記了包含'tcp_option.c',會發生什麼。如何讓我不要忘記'tcp_option.c'文件? – user1944267 2013-03-20 17:59:44

+0

你不應該包含'.c'文件,你必須鏈接它。如果您使用IDE,則應將其添加到項目中。 – deepmax 2013-03-20 18:27:22

-2

是的,你可以定義。請參閱以下代碼。

#include<stdio.h> 
typedef struct temp 
{ 
    int a; 
} temp; 
const temp test={5}; 
int main() 
{ 
    printf("%d",test.a); 
    return 0; 
} 
+0

他們在同一個文件中,我想要做的是定義一個獨立的頭文件 – user1944267 2013-03-20 17:43:28

+0

是的,即使這是可能的。只需將temp的結構和定義的聲明覆制到另一個文件temp.h中,並簡單地將#include「temp.h」複製到源文件中,然後在那裏使用這些文件... – 2013-03-20 17:46:24

+0

然後如果我包含此頭文件文件在同一個項目中的許多源文件中,這個const變量會被多次定義?我認爲應該增加一個'extern'? – user1944267 2013-03-20 17:49:24

相關問題