Unable to retrieve a value inside a c header file - c

I have a header file where a few functions needs to be implemented in the header file and included in a main.c file to be tested. These are some library functions of String and encoding.
Once these methods are implemented in the header file I should be able to include this file in another c file and execute these methods.
#ifndef ABSTRING_H
#define ABSTRING_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define ABSBLOCK 4096
typedef struct _abstring
{
unsigned char* val;
size_t length;
size_t space;
}absval;
abstring absval;
//Initialize string
abstring* initAbs() {
printf("%s", abval.val);
printf("%zu", abval.val);
abval.length = sizeof(abval.val);
abval.space = ABSBLOCK - sizeof(abval.val);
return &abval;
}
------------------ End of the header file (abString.h ) ------------------------
main.c file
#include "abString.h"
int main()
{
abstring absinit;
absinit.val = "abString";
printf("ABSBLOCK block size : %d .\n", ABSBLOCK);
initAbs();
return 0;
}
The issue I'm having is once I define a val in the main c file I'm not able to retrieve that value inside my header file in order to initialize the length and space.

Related

How to manage global structs in c [duplicate]

This question already has answers here:
What exactly do C include guards do?
(3 answers)
Closed 4 years ago.
Honestly I'm not used to working in c and maybe I'm wrong as I approach the problem.
I have 3 files and I need to pass data from one to another
//main.c
#include <stdio.h>
#include "process.h"
#include "readFile.h"
int main() {
int numIn=2, numOut=1;
struct data *allData=readData(numIn, numOut);
process(allData, numIn, numOut);
return 0;
}
// readFile.h
#include <stdio.h>
#include <stdlib.h>
struct data {
double *in;
double *out;
};
struct data * readData(int numIn, int numOut) {
//here I initialize and fill an "allData" array of struct data
return allData;
}
//process.h
#include <stdio.h>
#include <stdlib.h>
#include "readFile.h"
int process(struct data * allData, int numIn, int numOut) {
return 0;
}
If I delete "process.h" and try to print "allData" in the main, the correct data are printed without errors, but when I try to process the data in "process.h" I get this compilation error:
In file included from C:\...\main.c:4:0:
C:\...\readFile.h:11:8: error: redefinition of 'struct data'
struct data
^
In file included from C:\...\process.h:11:0,
from C:\...\main.c:2:
C:\...\readFile.h:11:8: note: originally defined here
struct data
^
In file included from C:\...\main.c:4:0:
C:\...\readFile.h:24:15: error: conflicting types for 'readData'
struct data * readData(int numIn, int numOut)
^
In file included from C:\...\process.h:11:0,
from C:\...\main.c:2:
C:\...\readFile.h:24:15: note: previous definition of 'readData' was here
struct data * readData(int numIn, int numOut)
^
Do not place any code in the .h files
.h files are for the data declarations, extern variables declarations and function declarations.
.c files are correct place to have variable and functions definitions.
Move all the code form the .h files to .c files
Also add the .h file guards. It is just the definition. If this definition is already defined - it means that this file was already included and its content should be skipped
#ifdef MYGUARD_H
#define MYGUARD_H
/* .h file content
#endif

Define a variable in header file works only when extern keyword is not present? [duplicate]

This question already has answers here:
Variable declaration in a header file [duplicate]
(5 answers)
Closed 4 years ago.
I am learning at moment C and I really do not understand how header
files works and to be sure I have two Questions.
1) Let's take a look at the following program: main.c:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main( void )
{
printf( "Num = %d\n", number );
printNumber();
return 0;
}
functions.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
void printNumber( void )
{
printf("Number = %d\n", number );
}
functions.h:
#ifndef FUNCTIONS
#define FUNCTIONS
int number;
extern void printNumber( void );
#endif // FUNCTIONS
The way the program is in the Header file there is no extern keyword
involved so there seems to be reference to number and the program
Outputs:
Num = 0
Number = 0
The first Question is, does number get initialized (is number global
variable or similar if number is present only in the header file)
and is this a legal code/program?
Second scenario, let's take a look at the following code main.c:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int main( void )
{
printf( "Num = %d\n", number );
printNumber();
return 0;
}
functions.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
void printNumber( void )
{
printf("Number = %d\n", number );
}
functions.h:
#ifndef FUNCTIONS
#define FUNCTIONS
extern int number;
extern void printNumber( void );
#endif // FUNCTIONS
Here the program will not compile due the
`undefined reference to number`
Which force me to declare number in main:
#include <stdio.h>
#include <string.h>
#include "functions.h"
int number;
int main( void )
{
printf( "Num = %d\n", number );
printNumber();
return 0;
}
Which is the Right way and why?
Last thing, why does exactly not apply
to void printNumber( void ) as well. I see that it is working with
or without the extern keyword.
For the first version, in your header file, you define the variable number. That means every translation unit that includes the header file will have a definition of the variable. That's not allowed, you can only have a single definition spread over all translation units.
The solution to that problem is to declare the variable in the header file instead:
extern int number;
The use of the keyword extern marks this as a declaration instead of a definition, the compiler will know that the variable is defined somewhere else.
Then you of course need to define it somewhere. In one single source file put the definition:
int number;
I.e. exactly what you do in your last variant.
In addition to Some programmer dude's answer, I use the following construct:
// functions.h
#indef EXTERN
# define EXTERN extern
#endif
EXTERN int number;
// functions.c
#include "functions.h"
// main.c
#define EXTERN
#include "functions.h"
When main compiles, storage will be allocated for number. In all other source files, it will be declared as extern.

Multiple Definition of a function in C, Prototyping

Eclipse tells me that I have mutliple Definitions of a function.
I just can't spot the mistake.
This is my main.c
#include <stdio.h>
#include "kontaktverzeichnis.h"
int main(){
kontakt_hinzufuegen();
return 0;
}
This is the header:
#ifndef KONTAKTVERZEICHNIS_H_
#define KONTAKTVERZEICHNIS_H_
#include "kontaktfunktionen.c"
int kontakt_hinzufuegen();
#endif /* KONTAKTVERZEICHNIS_H_ */
and this is kontaktfunktionen.c
#include <stdio.h>
kontakt[];
kontakt_hinzufuegen(){
int i = 0;
printf("Bisher sind %i Kontakte angelegt.",kontakt[i]);
kontakt[i++];
}
struct kontaktname{
char* name;
char* vorname;
};
struct kontaktanschrift{
char* strasse;
int hausnummer;
int plz;
char* ort;
char* land;
};
Where is my error?
You're not supposed to #include C files, that's not the proper way to organize your code.
You should compile the C files separately and then link them together, or compile them all at once with a single compiler invocation.
Do not #include anything in your header file. And do a #include "kontaktverzeichnis.h" in the kontaktfunktionen.c file.
As #StoryTeller commented, define your kontakt_hinzufuegen() as int kontakt_hinzufuegen() in the kontaktfunktionen.c file and return an int value from the function kontakt_hinzufuegen as for ex::
#include <stdio.h>
#include "kontaktverzeichnis.h"
// define the type for this array as below
int kontakt[];
int kontakt_hinzufuegen(){
int i = 0;
printf("Bisher sind %i Kontakte angelegt.",kontakt[i]);
kontakt[i++];
// Return an int value
return 0 ;
}
Your error is that in kontaktfunktionen.h you are including kontaktfunktionen.c. This will include all the definitions and declarations from kontaktfunktionen.c which are already declared when you use kontaktfunktionen.c
As others have said: You should not include .c files in your header files.

No such file or Directory error for including header file C

I am trying to include a header file which contains a structure, but when I try to compile the file including the header file, I get No such file or Directory error. Both .c and header file are in the same directory.
Here is the code:
Header file "MyShared.h":
#ifndef MYSHARED_H_INCLUDED
#define MYSHARED_H_INCLUDED
#define PERM (S_IRWRU | S_IRGRP)
#define MySharedKey 0343
#define SIZE 2048
struct MyShared
{
char *buf[SIZE];
int ReadfromBuf,WriteToBuf,readbytes;
};
#endif
Mem.c file including the header file:
#include <sys/shm.h>
#include "MyShared.h"
int main()
{
MyShared *obj;
int shmid,i,childpid;
shmid = shmget(MySharedKey,sizeof(MyShared),NULL);
.....
}
Why am I getting this error?
In C, a struct definition is not a typedef.
#include <sys/shm.h>
#include "MyShared.h"
int main()
{
struct MyShared *obj;
int shmid,i,childpid;
shmid=shmget(MySharedKey, sizeof *obj, NULL);
.....
}
BTW: I don't think you want an array of pointers in shared memory: char *buf[SIZE];
should probably be char buf[SIZE];

Automatically replacing variables with #defines

I have a file with about 100 #defines in it, from 1-100, and each with a unique string value.
Now I'm trying to print this value, but instead of the value, I want to print what the #define is. For example:
#define FIRST_VALUE 1
var = FIRST_VALUE;
printf("%s", var);
and I want the printf to print FIRST_VALUE, not 1.
Is there any way to do this in C? Or must I just write out 100+ case blocks inside a switch statement?
You can use stringification to achieve what you are looking for:
#define FIRST_MACRO
#define MACRO_TO_STRING(x) #x
#include <stdio.h>
main() {
printf("%s\n", MACRO_TO_STRING(FIRST_MACRO));
}
This program will output:
FIRST_MACRO
After talking to one of my TA's at school, we've decided that the best way to do this would be to write an AWK script to process the header file and automatically generate all the case statements needed.
Thanks guys!
You can't do exactly what you want, since by the time the compiler gets the pre-processor output, the "ONE" token is long gone. However, if your goal is to write the list of constants once but generate both tokens and strings, then this can be done.
First, use a macro to build the constants as enums in a header file. File enums.h:
#ifndef ENUMS_H
#define ENUMS_H
#ifndef ENUM
#define ENUM(name,val) enum { name = val };
#endif
ENUM(ONE,1)
ENUM(TWO,2)
ENUM(THREE,3)
#endif /* ENUMS_H */
Second, redefine the macro in a .c file to create a string/integer mapping and include the .h file in the right place. File enums.c:
#include
#include
typedef struct {
char *str;
int val;
} DescriptiveEnum;
static DescriptiveEnum enums[] = {
#define ENUM(name,val) { #name, val },
#include "enums.h"
};
#define NUM_ENUMS (sizeof(enums)/sizeof(enums[0]))
char *enum_to_str(int val)
{
int i;
for (i=0;i<NUM_ENUMS;i++) {
if (enums[i].val == val) return enums[i].str;
}
return "";
}
Now both the enum constants and the mapping function are available to callers. File main.c:
#include <stdio.h>
#include <stdlib.h>
#include "enums.h"
char *enum_to_str(int val);
int main(int argc, char *argv[])
{
int val;
val = ONE;
printf("%d %s\n",val,enum_to_str(val));
return EXIT_SUCCESS;
}

Resources