#including files [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I got a problem with including files.
What I've basically made is a command-line program in C that works with a csv file. It has 5 commands: -menu, -add, -edit, -del, -verify. All is good except for the -menu. What needs to happen when I type "./passweb -menu" is for a visual menu to appear. This menu command should call a new function and it needs to be located in a separate c file (aka menu.c).
The problem I'm having right now is that I'm not too sure how to include the files to run in the menu.c because the way I have it set up right now, passweb.c has all the functions such as -add and -edit and etc. I know you need to make header files and such but it's complaining that I've declared the methods twice which is true since I use the functions in the menu file.
Here's some of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cipher.h"
#include "menu.h"
#include "passweb.h"
#define MAXLENGTH 51 //longest length of a single record + 1 =51 bytes
#define SIZEOFDB 1000
#define ENCRYPT 5
typedef struct rec
{
char name[MAXLENGTH];
char pw[MAXLENGTH];
char type[6];
int boolean;
}RECORD;
int add(char *nName, char *nPw, char *nType, RECORD *arr, int size);
void del (char *tName, RECORD *arr, int size);
int edit(char *nName, char *nPw, char *nType, char *tName, char *tPw, RECORD *arr, int size);
int verify (char *tName, char *tPw, RECORD *arr,int size);
This is my main file "passweb.c" and it's declared the functions.
Later on in the main, I will call a menu function which is located in a menu.c file.
In the menu function I use "add","edit","del" and etc that I wrote in this .c file.
As you can see on the top, I have included the header files.
What can I do to solve this problem?
Sorry for the long post.
Thanks

You should put function prototype in the header file. You should put its implementation in the source file, which should include the header file.
For example, the header (test.h) would have the structure definitions and function prototypes like:
#ifndef TEST_H
#define TEST_H
struct myStruct {
int x;
};
int Add(int lhs, int rhs);
#endif
And the source would have:
#include "test.h"
#include <stdio.h>
int Add(int lhs, int rhs)
{
return lhs+rhs;
}
int main()
{
printf("%d",Add(2,3));
return 0;
}

put this in your header file and include it:
#ifndef FUNCS_H_
#define FUNCS_H_
int add(char *nName, char *nPw, char *nType, RECORD *arr, int size);
void del (char *tName, RECORD *arr, int size);
int edit(char *nName, char *nPw, char *nType, char *tName, char *tPw, RECORD *arr, int size);
int verify (char *tName, char *tPw, RECORD *arr,int size);
#endif /*FUNCS_H_*/
the #ifdef guards the header from multiple inclusion

Move the declaration of add, del, edit and verify in a new include file main.h
Include main.h in your main .c file and in menu.c
In general is also a good idea to put directives in the include files that tells the preprocessor to use them only once - Visual C++ has a special #pragma once directive for that, otherwise you can use
#if ! __MENU_C
#define __MENU_C
. . . .
#endif

The header file should contain your function prototypes and the necessary information about the data types they reference, such as your struct definitions. It may also include #define'ed constants, inline functions, declarations of extern variables (which would be declared normally inside one of your .c files), etc.
Once you have these things in your header file, you can remove them from the .c file(s); the actual function definitions, with the bodies, should be in the .c files -- but don't duplicate the prototypes there. You then #include the header in each .c file that needs the functions, etc. declared in it.
You also need to ensure that the items in the header file don't get #include'ed more than once in each source file, even indirectly (included from another include). Usually header guards are used for this, which use preprocessor conditionals to prevent processing of the header file when it has already been included:
#ifndef SOMEHEADER_H
# define SOMEHEADER_H
/* header file contents */
#endif
When compiling, you should be able to compile each .c file separately if you like, or all together if the compiler lets you. When linking, you need to link all the object files though. For gcc, doing both in one command, you might use something like this:
gcc -o program_name first.c second.c third.c
...which compiles each .c file to its own .o file, and links all of them together when producing the executable.

Related

need a workaround for a "multiple definition" error

A toy code illustrating my problem is as follows:
stuff.h:
#ifndef STUFF
#define STUFF
int a;
int testarr[]={1,2,3};
#endif
fcn.h:
#include "stuff.h"
int b[]={5,6,7};
void fcn();
main.h:
#include "stuff.h"
#include <stdio.h>
fcn.c:
#include "main.h"
void fcn() {
printf("Hello\n");
}
main.c:
#include "main.h"
#include "fcn.h"
int main() {
fcn();
printf("HI\n");
}
An attempt to compile fails with:
/g/pe_19976/fcn_2.o:(.data+0x40): multiple definition of `testarr'
/g/pe_19976/main_1.o:(.data+0x40): first defined here
After doing some reading, I realize that defining the array testarr in the header file is a problem. But the thing is, in my real code, several files need access to testarr and it needs to have the same assigned values everywhere. I guess I could put it in main.h (?) but even if that would work, in my real code it logically belongs in stuff.h. How do I solve this conundrum?
BTW, based on something else I found, I tried defining testarr as extern but got the same problem.
When you put a variable definition into a header file, any .c file that includes it will have a copy of that variable. When you then attempt to link them, you get a multiple definition error.
Your header files should contain only a declaration of the variable. This is done using the extern keyword, and with no initializer.
Then in exactly one .c file, you put the definition along with an optional initializer.
For example:
main.c:
#include "main.h"
#include "fcn.h"
int a;
int testarr[]={1,2,3};
int main() {
fcn();
printf("HI\n");
}
stuff.h:
#ifndef STUFF
#define STUFF
extern int a;
extern int testarr[];
#endif
fcn.h:
#include "stuff.h"
extern int b[];
void fcn();
fcn.c:
#include "main.h"
int b[]={5,6,7};
void fcn() {
printf("Hello\n");
}
It is not clear why you are using so many global variables. The array
int testarr[]={1,2,3};
is defined as many times as there are compilation units (in your example there are at least two compilation units) that include the corresponding header.
Declare the array in a header like
extern int testarr[3];
and define it in a cpp module.
int testarr[]={1,2,3};
The same is valid for other global variables that have external linkage.
As for this remark
BTW, based on something else I found, I tried defining testarr as
extern but got the same problem.
Then the array with the specifier extern shall not be initialized in a header. Otherwise it is a definition of the array.

Header Files in C

I have been reading about C for a while now and decided lets write a little add program, nothing fancy at all. My understanding of C headers is that they are "interfaces" (such as like java and other languages) but where you can also define variable that either have set values or not..
So I wrote this:
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int main(int argc, char** argv) {
printf("hello World\n");
add(12, 18);
return (EXIT_SUCCESS);
}
int add(int a, int b){
int value = a+b;
printf("value = %d\n", value);
return 0;
}
It has a header file that looks like such:
#ifndef SAMPLE_H_GUARD
#define SAMPLE_H_GUARD
int add(int a, int b);
#endif
I thought header files, and this is where I am lost on their definition, was suppose to define the use of add, so all I would have to do is call add - From my understanding, I define the rules of add and then implement the functionality of add....
Also, A lot of the material I have read shows one header file for multiple C files. where as a lot of projects today have one header per one c, meaning Sample.h belongs to Sample.c and nothing else.
Can some one shed some light on this?
Could I have done this like so:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int main(int argc, char** argv) {
printf("hello World\n");
add(12, 18);
return (EXIT_SUCCESS);
}
add.c
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int add(int a, int b){
int value = a+b;
printf("value = %d\n", value);
return 0;
}
sample.h
#ifndef SAMPLE_H_GUARD
#define SAMPLE_H_GUARD
int add(int a, int b);
#endif
I believe in the book I was reading: C Programming Language they had a calculator example split up like this, my question is how does C know where add is defined? It knows the rules for it based on the header file, i think, but not where the actual implementation is ....
There example where they split of the files like such doe not have something like #include "add.c" all they do is include the header file in the files that either implement or use this functionality.
Note: obviously the calculator example and my example are going to be different but fundamentally the same - for those who have the book. I am just lost on how to use header files effectively and efficiently.
A header file in C would declare the function add for those modules that need it, but not define the function. The function is still to be defined in its own module (e.g., in your case, add.c).
So in general, to make a function foo available to several modules, you would normally:
Choose a header file (maybe it's own if there are other associated
defines, etc) to declare foo. For example, perhaps foo.h would
have void foo(...);
In some module, perhaps foo.c, you would define the complete
function foo.
In any module that wants to call foo, you would #include "foo.h"
(or whatever header you used) and call the function.
When you compile/link the code, you would make sure all modules,
including foo.o or whatever module has foo defined in it, were
present.
A declaration, given in the header file, provides (of course) the function name, the function return type as well as listing all the parameters and their types. This is all the compiler needs to know to figure out how to call the function from the calling module. At link time, addresses are all resolved so that the modules then know exactly where the function is in its own particular module.
My understanding of C headers is that they are "interfaces" (such as
like java and other languages) but where you can also define variable
that either have set values or not..
This is not correct. You cannot "define" variables - well, you can but that will cause multiple definitions error while compiling code if you include header more than once.
Could I have done this like so:
Regarding your code - both variants are correct. C language uses headers to read declarations and hence headers are optional as well. You can have your code split into as many as you want .h and .c files. Compiler will create an object file for each .c file. All .h files included in a c file are basically embedded in that C file "before compilation" i.e. in preprocessing phase. Linker then comes in picture which combines objects to produce the executable.
Please don't hesitate if something is not clear in my answer.

Experimenting with global variables and functions in C

I'm trying to understand how global variables and functions work in C. My program compiles and works fine with gcc, but does not compile with g++. I have the following files:
globals.h:
int i;
void fun();
globals.c:
#include "stdlib.h"
#include "stdio.h"
void fun()
{
printf("global function\n");
}
main.c:
#include "stdlib.h"
#include "stdio.h"
#include "globals.h"
void myfun();
int main()
{
i=1;
myfun();
return 0;
}
And finally, myfun.c:
#include "stdlib.h"
#include "stdio.h"
#include "globals.h"
void myfun()
{
fun();
}
I get the following error when compiling with g++:
/tmp/ccoZxBg9.o:(.bss+0x0): multiple definition of `i'
/tmp/ccz8cPTA.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
Any ideas why? I would prefer to compile with g++.
Every file you include globals.h from will define "int i".
Instead, put "extern int i;" into the header file and then put the actual definition of "int i = 1;" in globals.c.
Putting header guards around globals.h would be sensible too.
Edit: In answer to your question its because a #include works kind of like a cut and paste. It pastes the contents of the included file into the c file that you are calling include from. As you include "globals.h" from main.c and myfun.c you define int i = 1 in both files. This value, being global, gets put into the table of linkable values. If you have the same variable name twice then the linker won't be able to tell which one it needs and you get the error you are seeing. Instead by adding extern on the front in the header file you are telling each file that "int i" is defined somewhere else. Obviously, you need to define it somewhere else (and ONLY in one place) so defining it in globals.c makes perfect sense.
Hope that helps :)
I would add an include guard in your globals file
#ifndef GLOBALS_H
#define GLOBALS_H
int i;
void fun();
#endif
Edit: Change your globals to be like this (using extern as the other answer describes)
globals.h
extern int i;
extern void fun();
globals.c
#include "stdlib.h"
#include "stdio.h"
int i;
void fun()
{
printf("global function\n");
}
I compiled it with
g++ globals.c main.c myfun.c
and it ran ok
Several things wrong here; several other things highly recommended:
globals.h:
#ifndef GLOBALS_H
#define GLOBALS_H
extern int my_global;
#ifdef __cplusplus
extern "C" {
#endif
void fun();
#ifdef __cplusplus
}
#endif
#endif
/* GLOBALS_H */
globals.c:
#include <stdlib.h>
#include <stdio.h>
#include "globals.h"
int my_global;
void fun()
{
printf("global function: %d\n", my_global);
}
main.c:
#include <stdlib.h>
#include <stdio.h>
#include "globals.h"
void myfun();
int main()
{
my_global=1;
myfun();
return 0;
}
void myfun()
{
fun();
}
You should declare "extern int myvar" in your header, and actually allocate "int myvar" in one and only one .c file.
You should include "globals.h" in every file that uses "myvar" - including the file where it's allocated.
Especially if you're planning on mixing C and C++ modules, you should use 'extern "C"' to distinguish non-C++ functions.
System headers should be "#include <some_header.h>"; your own headers should use quotes (#include "myheader.h") instead.
Short variable names like "i" might be OK for a strictly local variable (like a loop index), but you should always use longer, descriptive names whenever you can't avoid using a global variable.
I added a "printf" for my_global.
'Hope that helps!
I had this problem when porting some old C code to C++. The problem was it was a project that was connected to a database, and i wanted to port the database to c++ but not the rest. The database pulled in some C dependencies that couldn't be ported, so i needed the C code that overlapped both the database and the other project to compile in g++ as well as gcc...
The solution to this problem is to define all variables as extern in the .h file. then when you compile in either gcc or g++ it will report symbols missing in the .c files. So edit the .c files in the error messages and insert the declaration into all the .c files that need the variables. Note: you may have to declare it in multiple .c files, which is what threw me and why I was stuck on this problem for ages.
Anyway this solved my problem and the code compiles cleanly under both gcc and g++ now.

Sharing variables across files in C

I have two files:
hudwidgets.c
#include "osd.h"
#include "osdadd.h"
#include <stdio.h>
struct TextSize tsize;
char buff[50];
void hud_draw_lin_compass(int cx, int cy, int tick_maj, int tick_min, int range, int heading)
{
.. important code that uses buff ..
}
hud.c
#include "hudwidgets.h"
#include "hud.h"
#include "osd.h"
#include "osdadd.h"
.. some code ..
void hud_rc_plane_single_frame()
{
fill_mem(0x0000);
if((frame / 50) % 2 == 0)
{
get_next_warning(buff);
}
.. some more code ..
}
The problem I have is that when I try to compile this, the compiler complains of no buff defined, but when I try to define it, the linker complains of two buff variables. Catch-22. To this end, I am asking two questions:
how to fix this, and;
if it is possible to use the same variable thus saving memory because only one variable needs to be allocated (working with a memory constrained microcontroller.)
You need this in the top of hud.c, and any other .c file you use them from:
extern struct TextSize tsize;
extern char buff[50];
The extern keyword tells the compiler that the "actual" variables already exist, in some other unit (file), and the linker will fix it all up for you in the end.
If you're doing this on a large scale in a project, consider how you might encapsulate globals in one place, and create a shared .h file that declares these things as "extern" for all the places that you use them from.
use "extern char buff[50];" in the files where you have not initialized the buff and want to use it. This tells that the declaration is done in other files and you are using it in this file.

C: Inclusions within Headers

If I have the following:
/*
* example.h
*/
#ifndef EXAMPLE
#define EXAMPLE
#include <stdio.h>
extern int parse_string(FILE *, char const*, const unsigned int);
#endif
Will this mean that code that uses ... #include example.h ... won't have to ... #include example.h's ... dependencies ? ( ie: #include <stdio.h> )
Yes
But if the code depends on <stdio>, it probably should include it. (After all, <stdio> has multiple inclusion protection as well.)
If what you want is a master include for your project, then go ahead and make one, but have it include both the actual headers and the common system headers, but no prototypes or declarations or macros. That is, have the mega include do nothing but includes. This way individual modules can make their own decisions down the line as the program evolves.
Correct - this is why its good practice to limit necessary headers included within other headers. The preprocessor will replace the "#include" directive with the contents of stdio.h,
so your header will look something like this to the compiler:
/*
* example.h
*/
#ifndef EXAMPLE
#define EXAMPLE
<contents of stdio.h>
extern int parse_string(FILE *, char const*, const unsigned int);
#endif
Yes, you can do that and it will have the desired effect.
For your particular example you need FILE declared in <stdio.h>, so it's good to include it.
If the parse_string() prototype used size_t instead of unsigned int and const char * (for a filename) instead of FILE *, I'd include <stddef.h> in the "example.h"
#ifndef EXAMPLE
#define EXAMPLE
#include <stddef.h> /* size_t typedef */
extern int parse_string(const char *filename, char const*, const size_t);
#endif

Resources