This is a header file
#include <stdio.h>
int m = 18;
int x = 4;
int singles (n) {
if (n == 1)
return 0;
return doubles(n-1);
}
int doubles (n) {
if (n == 1)
return 0;
return triples(n-1);
}
int triples (n) {
if (n == 1)
return m;
return (singles(n-1) + doubles (n-1) + triples (n-1))*(m-1);
}
and this is the main file
#include <stdio.h>
#include "test.h"
int main () {
printf("%d",singles (x));
}
So this is pretty complicated for me at-least.The idea is that in the main function i will call singles(x) where x =4 so its more like singles (4),it will call doubles (3),that will call triples (2),that will call all of singles(1) which will return 0,doubles (1) that returns 0 and triples (1) that will return m.
So the error i am getting is
./test.h:13:12: warning: implicit declaration of function 'doubles' is invalid
in C99 [-Wimplicit-function-declaration]
return doubles(n-1);
^
./test.h:20:12: warning: implicit declaration of function 'triples' is invalid
in C99 [-Wimplicit-function-declaration]
return triples(n-1);
^
2 warnings generated.
I tried to create a header file .h with the first script and then made a second .c script that i try to compile that won't work.I tried importing the header to try to avoid this error but it doesn't seem to work.
Thanks a lot
Inside of singles, you're using doubles before it's defined. Similarly in doubles, you're using triples before it's defined. That's why you're getting the implicit declaration errors.
Also, you're not defining the type of the n parameter to any of these functions.
You need to specify function prototypes, which declare the function without defining it:
int singles(int n);
int doubles(int n);
int triples(int n);
Also, you shouldn't define functions in a header file. If you include this header in multiple .c files and then link them together, you'll get an error because you'll have multiple definitions of those functions.
Take all of the function definitions and put them in test.c. Then in test.h, put only the prototypes above. Then you can compile everything as follows:
gcc -c test.c
gcc -c main.c
gcc -o main main.o test.o
Or in a single line:
gcc -o main test.c main.c
The term "implicit declaration" in an error message is usually generated when the compiler sees the implementation of a call to a function before the declaration (prototype).
For example, you should have:
header file
int singles(int x);
int doubles(int x);
int triples(int x);
In your source file:
#include "header_file.h"
Also, in your function definitions (implementations) you need to specify the type of the argument:
int singles (/* data type */ parameter_name)
{
//...
}
Edit 1: Changed implementation to function call per #John Bollinger.
Related
I need to know what is meant by "Header" in C language? is it:
an area in the code, like header area in HTML code (a title> or declaration area? or definition area?, or kind of)?
or it is like a function (can be: function, or sub routine, or a scope, or kind of) that can be called.
A header is a convention generally accepted by C programmers.
It is a usually a .h file which is included into C source files which provides several benefits.
1.- Provides declaration of data types, global variables, constants and functions.
So you don't have to rewrite them time and again. And if they need being changed you just need to change it in a single file.
In example this program composed of two compliation units (two .c files) compiles and runs just fine.
// File funcs.c
#include <stdio.h>
struct Position {
int x;
int y;
};
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
// File main.c
struct Position {
int x;
int y;
};
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
}
But it is more mantainable to have the declaration for the struct Position in a header file and just #include it everywhere it is needed, like this :
// File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
struct Position {
int x;
int y;
};
#endif // FUNCS_H
//File funcs.c
#include <stdio.h>
#include "funcs.h"
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
//File main.c
#include "funcs.h"
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
2.- Provides some type safety.
C features implicit declaration of functions. A "feature" (or rather an arguable language design mistake) which was fixed in C99.
Consider this program composed of two .c files :
//File funcs.c
#include<stdio.h>
int f(long n)
{
n = n+1;
printf("%ld\n", n );
}
// File main.c
int main(void)
{
f("a");
return 0;
}
With gcc this program compiles without warnings or errors. But does not behave as we could reasonable expect and desire :
jose#cpu ~/t/tt $ gcc -o test *.c
jose#cpu ~/t/tt $ ./test
4195930
Using a header file like this :
//File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
int f(long n);
#endif // FUNCS_H
//File funcs.c
#include<stdio.h>
int f(long n) {
n = n+1;
printf("%ld\n", n );
}
// File main.c
#include"funcs.h"
int main(void) {
f("a");
return 0;
}
The program still compiles and works wrong but at least we get a warning :
jose#cpu ~/t $ gcc -o test *.c
main.c: In function 'main':
main.c:5:5: warning: passing argument 1 of 'f' makes integer from pointer without a cast
f("a");
^
In file included from main.c:2:0:
funcs.h:3:5: note: expected 'long int' but argument is of type 'char *'
int f(long n);
^
jose#cpu ~/t $ ./test
4195930
3.- Provide a public interface while letting the implementation details remain hidden.
When you design your program it is desirable to make it modular. That is to ensure that different parts of it (modules) are as independient as possible. So that when you need to make a change to one module you need not be worried about such change affecting other modules
Headers help in doing this because you put in the header of a modules the data structures, function prototypes and constants that will be needed by the users of such module.
The implementation details go into .c files.
That is how libraries work. The API interface is specified and distributed in header files. But the API code is in .c files which don't need to be distributed. As an user of the library you just need the headers and the compiled library, not its source code.
What is C header Linguistically?
Referring linguistically I'd say a C header file describes the interface as provided by a translation unit, namely the accompanying C file.
"interface" by means of
types
constants
(global) variables
functions
Not all of the above need to be part of a C header.
C headers are optional from the C language's perspective, but by convention they are expected to exist.
a header is a file with the .h extension.
It is meant to help the compiler to understand the symbol (method, function, struct, variable...) that are used within the code. See of it like an glossary at the end of a book.
It is used solely for development purpose.
It helps develloper knowing what function are available without having to look in all the implementation file. Like a man page.
A search on google? http://www.tutorialspoint.com/cprogramming/c_header_files.htm :)
Usually when talking about "headers" in C, what is meant is the files you include with the #include preprocessor directive. Those are called header files.
It could also be other things, like a comment at the top of a source (or header file) could be header. A comment before a function could be a function header.
Or when reading data files or data over the internet, many protocols have the data split into a header and the actual data (see e.g. HTTP).
I have two files.
The first file contains the function prototype and the main function calls myfunc with only one argument:
int myfunc (int x);
int main ()
{
int x =5;
myfunc(x);
}
and the second file contains the function definition but with 2 arguments:
int myfunc (int x, int y)
{
return x+y;
}
When I tried to compile this two files using GCC I got no errors or warnings.
How to force GCC to warn about something like this??
Put your prototypes in a header file, and #include the header file in all source files which use the functions.
GCC compiles each file independently, so it cannot know that the definition of the function does not correspond to the declaration unless the declaration is also included in the file with the definition.
It should look like this:
myfunc.h
#ifndef MYFUNC_H
#define MYFUNC_H
int myfunc (int x);
#endif
myfunc.c
#include "myfunc.h"
int myfunc (int x, int y)
{
return x+y;
}
main.c
#include "myfunc.h"
int main ()
{
int x =5;
myfunc(x);
}
Because the two source files are two different translation units that are compiled completely separately, it's impossible for the compiler to know about this. And as C symbols doesn't really have information about arguments, the linker can't warn about this either.
The only solution is to put function prototypes in header files that are included in all relevant source files.
I'm still learning C and I understand that to get rid of most implicit declaration warnings, you add the prototype header at the beginning. But I'm confused as to what you do when you have outside methods being used in your code.
This is my code when I'm using the outside methods
#include <stdio.h>
#include <string.h>
int main(void)
{
int arrayCapacity = 10;
int maxCmdLength = 20;
int A[arrayCapacity];
int count = 0; /* how many ints stored in array A */
char command[maxCmdLength + 1];
int n;
while (scanf("%s", command) != EOF)
{
if (strcmp(command, "insert") == 0)
{
scanf("%d", &n);
insert (n, A, arrayCapacity, &count);
printArray(A, arrayCapacity, count);
}
else if (strcmp(command, "delete") == 0)
{
scanf("%d", &n);
delete(n,A,&count);
printArray(A, arrayCapacity, count);
}
else
{
scanf("%d", &n);
printArray(A, arrayCapacity, count);
}
}
return 0;
}
The methods printArray, insert, and delete are all in the form of: printArray.o, insert.o, delete.o
This is how I compiled my program: gcc -Wall insert.o delete.o printArray.o q1.c
and I get these warnings:
q1.c: In function âmainâ:
q1.c:20: warning: implicit declaration of function `insert'
q1.c:21: warning: implicit declaration of function `printArray'
q1.c:30: warning: implicit declaration of function `delete'
I've tried including this in headers but I get errors saying file or directory not found.
Any help appreciated.
Put them in a header file foo.h like so:
extern void printArray(int *A, int capacity, int count);
...
then include that file in your source
#include "foo.h"
You need to include the correct headers to get rid of such warnings.
If you get a "file not found" error, try to include them as
#include "myheader.h"
and put your header files in the same directory as your source code.
Generally speaking, #include "file" is for programmer-defined headers while #include <file> is or standard headers.
You should be able to just put in the function prototype at the top of the file like you do for other functions in the same file. The linker should take care of the rest.
Where did you get those .o files from? If you have written them yourself, then you should create the corresponding .h files. If you got these files from somewhere else, then you should search for the headers in the same place.
If all called functions are written before the main() function the compiler will know their name, return type and parameter signature and can match all three of these properties with each following function invocation.
Some programmers like to write a function signature first, and do the implementation at a later time.
The only time a function declaration is essential is when using co-routines: functionA invokes functionB which in turn invokes functionA.
Done as follows:
type a(...signatureOfA...)
/* compiler now knows about a() */
type b(...signatureOfB...)
{…
// implementation of b
a(…arguments for a…);
/* compiler knows about above */
…}
type a(...signatureOfA...)i
{…
// implementation of a
b(…arguments for b…);
/* compiler knows about above */
…}
int main()
{
a(… arguments for a…);
/* compiler knows */
return(code);
}
I am heaving a weird issue with inlining functions defined in different files. Consider the following scenario.
in main.c:
#include "inline.h"
int main(void) {
int i = 0;
for (i = 0; i<=100000; i++) {
omfg(i);
}
return 0;
}
in inline.h:
inline int omfg(unsigned int num);
and in inline.c:
#include <stdio.h>
inline int omfg(unsigned int num) {
int i = 0;
for (i = 0; i<= 10; i++) {
printf(".");
num++;
}
return num;
}
When I compile with gcc using something similar to:
$ gcc inline.c main.c -o binary -Wall -Winline -Wextra -O2
I get:
main.c: In function 'main':
inline.h:2: warning: inlining failed in call to 'omfg': function body not available
main.c:7: warning: called from here
What am I doing wrong? Should I declare omfg() in a different way? Its quite puzzling...
Move the implementation to the header file. You can declare the function up front then define it below, or even #include a special file like inline.inl at the bottom of the header to hide it, but fundamentally the function definition needs to be available if it's to be inline.
You must put the implementation of your inline function in the header file if you want this to compile.
I declared a variable i in temp2.h
extern i; which contains just one above line
and made another file
temp3.c
#include<stdio.h>
#include<temp2.h>
int main ()
{
extern i;
i=6;
printf("The i is %d",i);
}
When I compiled above as
cc -I ./ temp3.c I got following errors
/tmp/ccJcwZyy.o: In function `main':
temp3.c:(.text+0x6): undefined reference to `i'
temp3.c:(.text+0x10): undefined reference to `i'
collect2: ld returned 1 exit status
I had declared extern in temp3.c above as K R page 33 says as I mentioned in above post.
I tried another way for temp3.c with same header file temp2.h
#include<stdio.h>
#include<temp2.h>
int main ()
{
i=6;
printf("The i is %d",i);
}
and compiled it cc -I ./ temp3.c and got following error
/tmp/ccZZyGsL.o: In function `main':
temp3.c:(.text+0x6): undefined reference to `i'
temp3.c:(.text+0x10): undefined reference to `i'
collect2: ld returned 1 exit status
I also tried
#include<stdio.h>
#include<temp2.h>
int main ()
{
extern i=6;
printf("The i is %d",i);
}
compiled this one
cc -I ./ temp3.c
got same error as in post 1
temp3.c: In function ‘main’:
temp3.c:5: error: ‘i’ has both ‘extern’ and initializer
So I have tried at least 3 different ways to use extern but non of them worked.
When you declare a variable using extern , you are telling the compiler that the variable was defined elsewhere and the definition will be provided at the time of linking. Inclusion is a different thing altogether.
extern
An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context.
-The C Programming Language
A variable must be defined once in one of the modules(in one of the Translation Units) of the program. If there is no definition or more than one, an error is produced, possibly in the linking stage (as in example 1 and 2).
Try something like the following
a.c
int i =10; //definition
b.c
extern int i; //declaration
int main()
{
printf("%d",i);
}
Compile, link and create an executable using
gcc a.c b.c -o executable_name
or
gcc -c a.c // creates a.o
gcc -c b.c // creates b.o
Now link the object files and create an executable
gcc a.o b.o -o executable_name
extern is declaration mechanism used to tell the compiler that the variable is defined in another file.
My Suggestion is that you define a variable in a ".c" file and then add the extern declaration in the corresponding ".h" file. In this way, the variable declaration will be available to all the source files which includes this header file and also it will be easier for one to identify in which ".c" it is actually defined.
The first program said:
The variable i (implicitly of type int) is defined somewhere else - but you didn't define it anywhere.
The second program tried to use a variable for which there was no declaration at all.
The third program tried to declare a variable without an explicit type (used to be OK; not allowed in C99), and said:
The variable i is defined somewhere else, but I want to initialize it here.
You are not allowed to do that.
So, the compiler is correct in all cases.
The declaration in the header 'temp2.h' should be fixed to extern int i; first. The implicit int is long obsolete.
You could fix the first example in several ways:
#include <stdio.h>
#include <temp2.h>
int main()
{
extern int i;
i=6;
printf("The i is %d",i);
return 0;
}
int i;
This defines the variable after the function - aconventional but legitimate. It could alternatively be in a separate source file that is separately compiled and then linked with the main program.
The second example could be fixed with:
#include <stdio.h>
#include <temp2.h>
int main()
{
int i=6;
printf("The i is %d",i);
return 0;
}
It is important to note that this example now has two variables called i; the one declared in temp2.h (but not actually referenced anywhere), and the one defined in main(). Another way of fixing it is the same as in the first possible fix:
#include <stdio.h>
#include <temp2.h>
int main()
{
i=6;
printf("The i is %d",i);
return 0;
}
int i;
Again, aconventional placement, but legitimate.
The third one can be fixed by similar methods to the first two, or this variant:
#include <stdio.h>
#include <temp2.h>
int i;
int main()
{
extern int i;
i=6;
printf("The i is %d",i);
return 0;
}
This still declares i in <temp2.h> but defines it in the source file containing main() (conventionally placed - at the top of the file). The extern int i; insides main() is doubly redundant - the definition in the source file and the declaration in the header mean that it does not need to be redeclared inside main(). Note that in general, the declaration in the header and the definition in the source file are not redundant; the declaration in the header provides a consistency check with the definition, and the other files that also use the variable and the header are then assured that the definition in the file containing main() is equivalent to the definition that the other file is using too.