Header File being included twice - c

I am relatively new to C (as I don't want to use C++, or at least just yet) and I'm not sure how to fix my include error I am having.
I have a header file containing the constant value of 1000 and is called Test.
const int Test = 1000;
I have this file included in 2 files - Myfile.c and Myfile2.c each including the file as such:
#include "MyHeader.h"
My project will not build/compile and as I have found out it is including the header twice which is not allowed as I am declaring my variable "Test" twice. Upon research I found this on Wikipedia: http://bit.ly/10wPraP
I used this "Include Guard"
Example:
#ifndef MY_HEADER
#define MY_HEADER
const int Test = 1000;
#endif
and I have also tried the pre-processor(?) command pragma once.
#pragma once
However, my program still will not build. I now get error saying that the varibale "Test" is already defined in MyFile.obj.
I thought this might be a Visual Studio-ism as I am using that but both my 2010 Express C++ and VS2003 Professional wont build this. I have tried cleaning the project within Visual Studio and I am not sure what else to do.
Am I being very silly and missing something obvious here and that is why it isn't work?
I am used to C# and "using" with namespaces rather than includes. May my setting on VS to only compile C code be effecting this?

Include guards have nothing to do with it. You need to separate the declaration from the definition and have only one definition (this is called the "one definition rule", ODR):
header.h:
extern const int n;
one source file:
#include "header.h"
const int n = 1000;
all other source files:
#include "header.h"

Useful Reference:
Wikipedia on the extern keyword: https://en.wikipedia.org/wiki/External_variable
Wikipedia on the One Definition Rule: https://en.wikipedia.org/wiki/One_Definition_Rule
The problem is with the way that header files are processed when you #include them: Header files are literally copied and pasted into the body of your C files. This means that Myfile.c and Myfile2.c both have their own declarations of an int named Test - essentially creating two different versions of the one variable. The linker then complains about having two different variables with the same name.
The solution is to put the const int Test = 1000; in one of your C files, and to add extern const int Test; to MyHeader.h. This way, the variable is declared only once, and all files are aware of the one variable because the extern directive tells them that another file has the variable Test they are looking for.
MyHeader.h
extern const int Test;
Myfile.c (for instance)
#include "MyHeader.h"
...
const int Test = 1000;
Myfile2.c
#include "MyHeader.h"
...
<use Test>

This is correct. You have two source files that are defining Test. You should only define this once. Since header files get included all over the place, they should generally only declare variables, not define them. e.g.
header:
const int Test;
Exactly one c file:
const int Test = 1000;

Define that variable in any one of the .c file and declare that as extern in the header files.
#ifndef MY_HEADER
#define MY_HEADER
extern const int Test;
#endif
In Myfile.c define the variable
const int Test = 1000;

Related

How do I create a library in C?

I am working on a program that is using libgit2. I had kept the code in a single c file. Say:
somefile.c
I compile and use it. Now I want to separate some of the details related to libgit2 into a separate library inside the project. So I created an h file with the data structures that I need and the definitions of the functions I want to use. So far, nothing fancy: init stuff, pass in the path to the repo and s a treeish... those are const * constant.... then In the library c file I have an implementation of the functions in the .h file.
Currently, the layout is like this:
include/mylib.c
include/mylib.h
somefile.c
In include/mylib.h I have one struct and a couple of functions:
struct blah {} blah_info;
int blah_init(cont char * path, const char * treeish);
int blah_shutdown();
In include/mylib.c I include mylib.h:
#include "mylib.h" # notice that I don't have to use "include" in the path
And then I have definitions for the 2 functions that I put in the .h file.
In somefile.c now I am including the library c file, not the .h file (and no need to include git2.h anymore either as that is done in mylib files now).
#include "include/mylib.c"
And this allows me to compile and run the program, just like it did before I separated it into pieces but I know it's possible to include include/mylib.h from the original .c file. I think it requires to build the library before then going into compiling the final program? What steps are required for that?
Right now I'm compiling by hand in a shell script calling GCC in a single shot... so if I need to run more commands to do so, just let me know so that I add them to the script.
In somefile.c, you need to do this:
#include "include/mylib.h"
And make sure you define these functions in mylib.c:
int blah_init(cont char * path, const char * treeish) {
}
int blah_shutdown() {
}
And then declare them in mylib.h:
struct blah {} blah_info;
int blah_init(cont char * path, const char * treeish);
int blah_shutdown();
And when you compile, include both somefile.c and mylib.c as input files.
#include directive is used to insert content of a file somewhere else and it's mostly used to include headers so compiler knows what is what (types, constants, etc), then linker puts all compiled files into one single executable.
to make sure header is included only once to a single file you use something called conditional compilation, it's done with preprocessor (before compilation)
yourlib.h
#ifndef YOUR_LIB_H_ //there are many naming conventions but I prefer this one
#define YOUR_LIB_H_
//all your declarations go here
#endif //YOUR_LIB_H_
//you should put in comment what's that condition for after every endif
now in yourlib.c you include that header and then write your definitions
#include "yourlib.h"
//all your definitions go here
and same thing for your main file, just include the header and compiler knows what to do
#include "yourlib.h"
//your code goes here

Nsight Eclipse 5.5 identifier is undefined

In a project with many .cu files and a .h file, I have some constants defined in my main.cu like this (shown just one as example):
__device__ __constant__ unsigned int x[1];
#include "second.cu"
... some code...
In the file second.cu I am trying to use that constant, like this:
cudaMemcpyToSymbol(x, y, sizeof(xx));
But Eclipse is giving me the error: identifier "x" is undefined.
I noticed that #includes in my main.cu, like the header.h, I need to specifically add in all the .cu files again. Which produced some redefinition problems that I solved using #pragma once.
I am new to Eclipse in general, found some complains about the CDT regarding include files not being indexed. I tried the Index Rebuild/Update/Freshen/Re-resolve method that worked for some in this regard, but with no luck with my problems.
Also, tried disabling the 'heuristic resolution of includes' in Properties -> Indexer. I thought I got it for a few moments but then the error showed up again.
Any ideas to solve this problem?
This is a C/C++ problem and have nothing to do with CUDA.
Generally people don't include source files like .cu .cpp .c. Only header files like .h should be included.
If you have a global variable int x need to be referenced in many source files. You could define it in one souce file as
// main.cu
int x;
...
declare it in a header file as
// main.h
extern int x;
...
and include this header file in all the source files you will reference that variable as
// second.cu
#include "main.h"
void foo() {
int local=x;
}
...
and
// third.cu
#include "main.h"
void bar() {
int private=x;
}
...

What is wrong with using extern in C like that?

I've already searched something abou this but I've still don't understand it..
file1.h
extern int *game_array[5];
Player.c
#include "file1.h"
void *delete_player(player_struct *player)
{
... //some code
game_array[5] = 5; //undefined reference to `game_array`
... //some code
}
When I don't use extern it "work's fine" = I can build it withou errors, but the program's not finished ..
I suppose the using extern is fine but something is wrong ..
I want to use this game_array ... array of games on server from all my .c source files, there's only one instance of this array in my aplication.
You need to define game_array in one of your .c files, and compile/link that file into your executable.
The definition will look like this:
int *game_array[5];
What your file1.h is saying is basically "There exists a variable called game_array somewhere in my project, and it has such-and-such type". However, the variable doesn't actually exist until you've defined it somewhere (typically, in a .c file).
The extern keyword basically means that the compiler should not complain about the symbol, even if it's not defined, because it will be available at link-time.
So if it's not defined at link-time, you'll obviously have errors.
You need to provide an implementation in one of your C file:
Something like:
#include "file1.h"
int * game_array[ 5 ];
void * delete_player( player_struct * player)
{
...
Writing extern int *game_array[5]; means that somewhere, in some file, there's an actual definition for game-array -- i.e., a declaration without the extern. You're failing to provide that, so the linker complains that the actual variable doesn't exist anywhere.

how to define a variable in one file and use it in another one

The question may be very basic but I am not getting clue anyways ...
I have two files ...
and I am mentioning what I want to do .
file 1
...
j = data->alloc_len;
...
file 2
...
for(i=0;i<j;i++)
...
Its clear from above I want to assign value to a variable in one file and want to use that value in other file.
I tried #include "file1.c" in file2.c but it is giving lot of re-declaration errors.
I tried creating a seperate header file which only have one line int j and then included it in both files using extern but no benefit again.Although I think header files are meant for where i can create and assign a value to a variable in one file and then this value can be propogated to all other files by including this one.
May be I am wrong but I need it soon so please help me ...Thnx in advance.
Limitation -
The value can be assigned only through file1.c because data structure is declared and defined here only.I can not provide a value to variable j in a header file .
EDIT :
Although I mentioned but I think I could not clear my question.I have tried using it header files.
For debugging purpose I tried this ..
sample.h
extern int j;
file1.c
#include "sample.h"
int j=245;
file2.c
#include "sample.h"
printf("%d",j);
but its getting error .
Error I am getting is :
Couldn't open module sample.so, tried:
sample.so: cannot open shared object file: No such file or directory
./sample.so.so: cannot open shared object file: No such file or directory
/usr/local/lib/sendip/sample.so.so:
cannot open shared object file: No such file or
directory
/usr/local/lib/sendip/sample.so: undefined symbol: j
*none of the file contains main function actually *
Actually it is a very large project and I am using Makefile and all files will be linked at run time.
In short,the execution could be understood as there is a main.c file which contains main which in turns call file1.c and which in turn calls file2.c
About descriptive names I would say they are just for showing here otherwise I am already using descriptive name.
You could put this in a header file:
extern int j;
and only declare the "real" j in file1.c. If file2.c includes that header, then it can use variable j.
But, use descriptive variable names a the very least for globals. And you should avoid globals as much as you can, they are a liability in the long term, IMO.
(You could consider something like making a function in file1.c that returns that value. This has the advantage of assuring that j is controlled in file1.c, and only read in other places, limiting the complexity of understanding who "owns" that variable.)
like this
in the c file you define the variable say file1.c you write
int j;
...
j = data->alloc_len;
a header for your file1.h would contain
extern int j;
this header you include in file2.c
#include "file1.h"
but i would suggest using a more descriptive variable name.
#include "file1.c" is almost never the correct solution to a problem. Invariable you want to be declaring things in header files and then defining them in just a single source file.
file1.h
extern int j;
file1.c
#include "file1.h"
j = data->alloc_len
file2.c
#include "file1.h"
if (j>0)
...
Having said all of this, I would strongly council you to pass values as parameters rather than use global state. Global state is evil. Avoid it like the plague.

Separating a group of functions into an includable file in C?

I know this is common in most languages, and maybe in C, as well. Can C handle separating several functions out to a separate file and having them be included?
The functions will rely on other include files, as well. I want the code to retain all functionality, but the code will be reused in several C scripts, and if I change it once I do not wish to have to go through every script and change it there, too.
Most definitely! What you're describing are header files. You can read more about this process here, but I'll outline the basics below.
You'll have your functions separated into a header file called functions.h, which contains the following:
int return_ten();
Then you can have a functions.c file which contains the definition of the function:
int return_ten()
{
return 10;
}
Then in your main.c file you can include the functions.h in the following way:
#include <stdio.h>
#include "functions.h"
int main(int argc, char *argv[])
{
printf("The number you're thinking of is %d\n", return_ten());
return 0;
}
This is assuming that your functions.h file is in the same directory as your main.c file.
Finally, when you want to compile this into your object file you need to link them together. Assuming you're using a command-line compiler, this just means adding the extra definition file onto the end. For the above code to work, you'd type the follow into your cmd: gcc main.c functions.c which would produce an a.out file that you can run.
Declare the functions in header files and then implement them in .c files. Now you can #include the header files into any program that uses the functions and then link the program against the object files generated from the .c files.
Say you have a file with a function that you want to use elsewhere:
int func2(int x){
/*do some stuff */
return 0;
}
what you would do is split this up into a header file and a source file. In the header file you just have the function declaration, this tells the compiler that that function does exist, even if it is in a different file. The header might be called func2.h might look like this:
#ifndef HEADER_FUNC2_H
#define HEADER_FUNC2_H
int func2(int x);
#endif /*HEADER_FUNC2_H*/
The #ifndef HEADER_FUNC2_H part is to make sure that this only gets used once so that there are no multiple definitions going on.
then in the source func2.c file you have the actual function itself:
int func2(int x){
/*do some stuff */
return 0;
}
and in any other file now that you use func2 you have to include the header. You do this with #include "func2.h". So for example if we wanted to call func2 from randomfile.c it would be like this:
#include "func2.h"
/* rest of randomfile.c */
func2(1);
Then the last step is to link the object file that contains the function with the compiler when you compile.
If you want to reuse functions across multple programs, you should place them in a library and link it with the rest of your code.
If you want to share the same definitions (e.g. macros, types, ...) you can place them in a header file and include them with #include.
Please refrain from directly "#include" function code into a source file, it's a bad practice and can lead to very problematic situations (especially if you are a beginner, as your tag suggests).
Consder that normally when you have a set of functions you want to share and reuse, you will need both! You will usually end up with a myfuncs.lib (or libmyfuncs.a) library and a myfuncs.h header.
In the programs where you want to reuse your existing functions, you will include the header and link against the library.
You can also look at how to use dynamic libraries once you have mastered the usage of static libraries.

Resources