c header files

Pages: 12
Please can someone explain to me how to create my own header files

Thanks

Rodney
create a header file to define your functions or classes or whatever, create a cpp with the same name (for example hello.h and hello.c) in the .c (or .cpp) implement your stuff and when you need to use all implemented functions or classes include the .h file

example.h
example.cpp
main.cpp

in your main.cpp use
#include "example.h"
Header file a.h
1
2
3
4
5
6
#ifndef A_H_INCLUDED /* include guard */
#define A_H_INCLUDED

int a_function( int a, int b ) ; /* declare the function */

#endif /* A_H_INCLUDED */ 


C file a.c
1
2
3
4
5
6
7
8
#include "a.h" /* include the header */
#include <stdio.h>

int a_function( int a, int b ) /* implement the function */
{
    puts( "in a_function" ) ;
    return a + b*b ;
}


C file main.c
1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include "a.h" /* include the header */

int main()
{
    int i = 24 ;
    int j = 6 ;
    printf( "a_function returned %d\n", a_function(i,j) ) ; /* call the function */
}


Save a.h, a.c and main.c in the same directory.

Now, compile and link the two .c files to produce test.exe; run it.
1
2
>gcc -std=c11 -Wall -Wextra -pedantic-errors  -otest.exe *.c
>test.exe
To create one, just write couple of functions without the main() function.
Add header guards:
1
2
3
4
5
6
#ifndef YOURNAME_H
#define YOURNAME_H

//your functions, clasess and other definitions...

#endif 

They have extension .h
When you write program that uses this include, use #include "yourname.h". Use double quotes because it means that the program will look the include where you main .cpp file is stored.
Last edited on
Thank you all for the comprehensive answers but I am still very lost (feeling quite stupid actually)

For step one do I do the following

1. in the text editor save a file hello.h
2. Then go back to the text editor new and save a file hello.c
3. Then I write the code in another file and save it as main.c

After doing that I compile all three gcc hello.h hello.c main.c (I am really not sure here what to do)

Then when I write the final code I include the hello.h file in the code.

Thanks

Rodney
> After doing that I compile all three ...
> Then when I write the final code ...

The source code is written first and then, after that , it is compiled.

First read this tutorial: http://www.cs.utah.edu/~zachary/ispmma/tutorials/separate/separate.html
Make sure that you understand it; if not post a question.

Then, try to compile and link a.h, a.c and main.c in my earlier post.

Next, repeat the process with your hello.h, hello.c and main.c
Hi

I went through the tutorial several times and have encountered a problem at the very first instruction.

As instructed I downloaded the hello.c file saved it and then compiled as instructed

gcc -Wall -g -c hello.c

the following error code came back

hello.c:9 warning: return type of 'main' is not int

I also typed in the ls as instructed and I got the following error message

'ls' is not recognised as an internal or external command, operable program or batch file.

I am using the cmd prompt to compile in.

Not really sure what to do from here.

Thanks

Rodney

> hello.c:9 warning: return type of 'main' is not int

My mistake; I didn't check the code before posting the link. Sorry about that.
main() must return int; so modify hello.c

1
2
3
4
5
#include <stdio.h>

/*void*/ int main () {
  printf("Hello world\n");
}



> gcc -Wall -g -c hello.c

Prefer using these additional compiler options:
> gcc -std=c99 -Wall -Wextra -pedantic-errors -c hello.c
(If you have a recent version ogf GCC, you can use -std=c11 instead of -std=c99)



> 'ls' is not recognised as an internal or external command, operable program or batch file.

You are on Windows, to get information about the files in a directory, use dir instead of ls
Thank you

I made the changes

I tried to compile with gcc -std=c99 -Wall -Wextra -pedantic-errors -c hello.c

error message c99: No such files or directory

I then compiled with gcc -Wall -g -c hello.c a warning message of warning control reaches end of non-void function

Is it ok to carry on working through the tutorial or do I have another problem.

Many thanks for your patience and help

> I tried to compile with gcc -std=c99 -Wall -Wextra -pedantic-errors -c hello.c
> error message c99: No such files or directory

I suspect that you had left a space between the = and c99.
Write it without embedded spaces ie. -std=c99 and not -std = c99


> a warning message of warning control reaches end of non-void function

Compile with -std=c99 and the warning will go away. This was added to C in 1999:
reaching the } that terminates the main function returns a value of 0.



> Is it ok to carry on working through the tutorial or do I have another problem.

Continue to work through the tutorial; it is ok.
Hi below is exactly how I tried to compile the code and still get the error

c99 no such files or directory no input files

gcc -std=c99 -Wall -Wextra -pedantic-errors -c hello.c
@JLBorges: ¿why are you guarding function declarations?
> below is exactly how I tried to compile the code and still get the error

Ok. Add a return 0; to the end of main()

1
2
3
4
5
6
#include <stdio.h>

/*void*/ int main () {
    printf("Hello world\n");
    return 0;
}


And then compile with gcc -ansi -Wall -Wextra -pedantic-errors -c hello.c

Also, type just gcc --version at the command prompt. What does it print out in response?


> ¿why are you guarding function declarations?

I'm responding to the post:
Please can someone explain to me how to create my own header files

A header can contain definitions; even if it doesn't have one now, it may be added later; and drawing attention to include guards should be an essential part any explanation on creating header files.
Hence not just the include guard, but also the comment drawing attention to it: /* include guard */

Hi Thank you

I cut and pasted the command prompt gcc -ansi -Wall -Wextra -pedantic-errors -c hello.c

It compiled perfectly I am going to try and now work out what each instruction means in that line

gcc --version prints gcc (GCC) 3.4.2 (mingw-special) copyright (C) 2004 free software foundation, Inc.
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Hi piczim,

Just my 2 cents worth, in addition to JLBorges expert advice.

Seems you have a rather old version of gcc. The latest is 4.8 AFAIK but you might need to compile it yourself, otherwise you could find a binary version for your OS that is about v4.7.2. Any way try to get the latest version that you can.

This will enable you to have much better support for C11 or C++11, amongst other things.

Have a read of the manual to find out what the options mean, be sure to look at the manual for the version you are using :

http://gcc.gnu.org/onlinedocs/


There are zillion options, but the manual is well organised.

Hope all is well at your end 8+)
GCC 4.8.1 (MinGW) is can be downloaded from here: http://nuwen.net/mingw.html

These are the steps (reproduced from the section 'How To Install' on the web page):

1. Download http://nuwen.net/files/mingw/mingw-10.2-without-git.exe
2. Run mingw-10.2-without-git.exe
3. When it asks you for the directory to install into, type C:\GCC_4_8_1 and click 'Extract'
4. Wait for the installer to finish.

To compile programs with GCC 4.8.1, at the command prompt first type: C:\GCC_4_8_1\MinGW\set_distro_paths.bat

And then, carry on just as you have been doing with GCC 3.4.2
Sorry you going to go mad with me!

Followed the instructions to the "T" and all ok However I have my c file in the following

c:\prog\c\learn

Having extracted GCC 3.4.2 to my c drive I confirmed that the version is 4.8.1

I then thought best I extract the version 4.8.1 into the following destination c:\prog\c\learn the file is there but does not seem to have installed into that folder.

I am not sure how to install into this folder.



You do not need to install anything into the folder containing your files.

1. copy your three files (hello.h, hello.c, main.c) into a new folder; say c:\learn_c\new

2. Open a command window, cd c:\learn_c\new

3. Type C:\GCC_4_8_1\MinGW\set_distro_paths.bat

4. Type gcc --version
If your installation has gone well you would see gcc (GCC) 4.8.1 followed by some more lines of text

5. Compile your program with GCC 4.8.1: gcc -std=c11 -Wall -Wextra -pedantic-errors -c hello.c
Thank you now I can move on learning how to create my own headers
I don't want to detract from the subject at hand however just don't want to confuse myself from what I have learnt thus far.

the below code I have been using to learn with. I copied the code below into my new file where the gcc 4.8.1 is.

I tried to compile it with the following which I cut and pasted and amended from number 5. Above.

gcc -std=c11 -Wall -Wextra -pedantic-errors -c cur_con.c

When I tried to compile it as above I got the following

cc1.exe: error: unrecognised command line option '-std=c11'

I then tried to compile it using gcc cur_con.c -o cur_con and then I get a really weird message

c:\users\RODNEY~1\AppData\Local1\Temp\cc3o17Le.o:cur_con.c:<.text+0x2df>: undefined reference to sleep'

Before sending this message I checked it in the old directory and the program ran.

I amnot sure what went wrong as the hello program we have been working through worked no problem.

Many thanks

Rodney

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
  #include <windows.h>



enum 
  {
  black,
  dark_blue,
  dark_green,
  dark_cyan,
  dark_red,
  dark_magenta,
  dark_yellow,
  light_gray,
  dark_gray,
  light_blue,
  light_green,
  light_cyan,
  light_red,
  light_magenta,
  light_yellow,
  white
  };

int getcolors()
  {
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  GetConsoleScreenBufferInfo(
    GetStdHandle( STD_OUTPUT_HANDLE ), 
    &csbi
    );
  return csbi.wAttributes;
  }

int getfgcolor()
  {
  return getcolors() & 0x0F;
  }

int getbgcolor()
  {
  return getcolors() >> 4;
  }

void setfgcolor( int color )
  {
  SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ), 
    (getcolors() & 0xF0) | (color & 0x0F)
    );
  }

void setbgcolor( int color )
  {
  SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ), 
    ((color & 0x0F) << 4) | (getcolors() & 0x0F)
    );
  }

void setcolors( int fg, int bg )
  {
  SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ), 
    ((bg & 0x0F) << 4) | (fg & 0x0F)
    );
  }

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <windows.h>

int main()  {

int currencyOption;
int initial_fg_color = getfgcolor();
int initial_bg_color = getbgcolor();
start:
setbgcolor( white );
system("cls");
 setbgcolor( white );
  
setfgcolor( black );
printf("\n **************************************************");
printf("\n **************************************************");
printf("\n **                                              **");
printf("\n **     Enter the NUMBER from the below list     **");
printf("\n **    of currency you wish to convert to US$    **");
printf("\n **                                              **");
printf("\n **                                              **");
printf("\n **    1 = Australian dollars.                   **");
printf("\n **    2 = British Pounds.                       **");
printf("\n **    3 = Japanese yen.                         **");
printf("\n **    4 = South African Rand.                   **");
printf("\n **                                              **");
printf("\n **    Enter Currency number:                    **");
printf("\n **                                              **");
printf("\n **************************************************");
printf("\n **************************************************");
printf("\n");

scanf("%d", &currencyOption);
printf("\n");


float xrate;
if(currencyOption == 1) {
	xrate=0.914;
       printf("You want to convert Australian dollars to US$ \n"); }
if(currencyOption == 2) {
	xrate=1.656;
       printf("you want to convert British pounds to US$ \n"); }
if(currencyOption == 3) {
	xrate=0.010;
       printf("you want to convert Japanese yen to US$ \n"); }
if(currencyOption == 4){
	xrate=.101;
       printf("you want to convert vietnames dollars to US$ \n"); }
if(currencyOption > 4)
	goto start; 
sleep(3000);
system("cls");

setfgcolor( light_red );

printf("\n");
printf("\n **************************************************");
printf("\n **************************************************");
printf("\n **                                              **");
printf("\n **  Enter the amount you wish to convert to US$ **");
printf("\n **                                              **");
printf("\n **************************************************");
printf("\n **************************************************");
printf("\n");


	float currencyvalue;
printf("\n");

	scanf("%f",&currencyvalue);
	int i=1;
	float result[2];

			int mult = i* 1;
	result[i] = currencyvalue * xrate * mult;
	printf("\n");
	printf("\n");
	printf("To Be Converted:- %10.2f\n\nExchange rate of:-%10.2f \n\nYou will recieve:-%10.2f US$\n--------------------------------------------------\n", currencyvalue, xrate, result[i]);
sleep(4000);
system("cls");	
	printf("\n");
	int cont;
	int y;
	int n;

setfgcolor( light_green );
printf("\n **************************************************");
printf("\n **                                              **");
printf("\n **   Do you wish to perform another conversion  **");
printf("\n **           Type 1 for yes 2 for no            **");
printf("\n **                                              **");
printf("\n **************************************************");

printf("\n\n");


	
	scanf("%d", &cont);

	if(cont == 1)
	goto start;
	system("cls");
	if(cont== 2){
	printf("\n **************************************************\n\n");       
		printf("          HAVE A NICE DAY \n\n");
	printf("\n **************************************************\n\n");
	}


sleep(4000);
system("cls");

setfgcolor( light_blue );
	
printf("\n **************************************************");
printf("\n **                                              **");
printf("\n **  CODE written and compiled by Rodney Beadon  **");
printf("\n **                                              **");
printf("\n **************************************************");
printf("\n\n\n");
sleep(5000);
system("cls");




 
return 0; }

Last edited on
Pages: 12