3

I define several structures in a header file some structures have all thier members with constant values and some other structures have parts of their members with constant values

for those structures with constant members, is it possible to define a constant variable in the header file?

like in a header file tcp_option.h

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

so I want to define a constant variable, like

struct tcp_opt_nop opt_nop={ 0x01}; 

and then this variable can be used by other source files

6
  • Do you mean a define directive? Commented Mar 20, 2013 at 17:16
  • Can you give a code example? Commented Mar 20, 2013 at 17:19
  • 1
    Please show some code you are trying to compile. You can edit your original post and put the code in. Commented Mar 20, 2013 at 17:21
  • If you like down vote, don't modify your question. If not then provide some code example... Commented Mar 20, 2013 at 17:24
  • yes, I have added some example codes. Commented Mar 20, 2013 at 17:26

2 Answers 2

6

You should extern you variable.

.h file:

#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 file:

#include "hdr.h" const tcp_opt_nop opt_nop = {0x01}; 

main file:

#include "hdr.h" int main() { printf("%i\n", opt_nop.kind); // ... } 
Sign up to request clarification or add additional context in comments.

3 Comments

ah, I got it, you mean I need to create a tcp_option.c file, just wondering if I forgot to include tcp_option.c when compiling, what will happend. how to make me not forget the tcp_option.c file?
You shouldn't include .c file, you must link it. If you are using an IDE you should add it to your project.
Why not static const tcp_opt_nop opt_nop = {0x01}; in hdr.h? Assuming the address of the variable is not needed, then will this not make optimiser's job easier?
-3

yes, you can define. See the following code.

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

7 Comments

they are in the same file, what I want to do is to define a independent header file
yes, even that is possible. just copy the declaration of the struct and definition of temp to another file,say, temp.h and simply #include "temp.h" to your source file, where you want to use those...
then if I include this header file in many source files within the same project, will this const variable be defined multiple times? I think an extern should be added?
then use #ifndef TEMP_H #define TEMP_H at the top of your header file... and at the bottom of the file put #endif
Copying this into a header file will result in a linker error if you use it from two different source files.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.