0

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.

  • What error are you getting? – Richard Pennington Apr 05 '20 at 03:53
  • Headers should normally only contain declarations — of types and functions, mainly — and should not normally contain any definitions (such as a non-static, non-inline function). So, moving the function definition out of the header would be a good start. If the memory for an `abstring` is meant to be dynamically allocated, the `absinit.val` assignment in `main()` is bad news; that string cannot be freed. – Jonathan Leffler Apr 05 '20 at 04:32
  • Note that you should not, in general, create function, variable, tag or macro names that start with an underscore. Part of [C11 §7.1.3 Reserved identifiers](https://port70.net/~nsz/c/c11/n1570.html#7.1.3) says: — _All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use._ — _All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces._ See also [What does double underscore (`__const`) mean in C?](https://stackoverflow.com/q/1449181) – Jonathan Leffler Apr 05 '20 at 04:33
  • There is no global variable `abval` for the `initAbs()` function in the header to reference — this is a Good Thung™! You either need to pass (a pointer to) an `abstring` into the function or you need to dynamically allocate it inside the function and return a pointer to the allocated space. – Jonathan Leffler Apr 05 '20 at 04:36

0 Answers0