Home > Software design >  Implicit declaration of function with structs
Implicit declaration of function with structs

Time:11-04

I am trying to fix my last implicit declaration of a function by creating the prototype function in my header file. The lab is to write structs and currently I have my Main.c, RandomNums.h, and RandomNums.c. My function in RandomNums.c is finished but I'm not sure how I should write it in RandomNums.h

Below is what I have for my RandomNums.c file and the issue is that SetRandomVals is an implicit declaration in Main.c

struct RandomNums SetRandomVals(int low,int high) {
    struct RandomNums r;
    r.var1= (rand() % (high -low   1))   low;
    r.var2= (rand() % (high -low   1))   low;
    r.var3= (rand() % (high -low   1))   low;
     
    return r;
}

Below is how I called SetRandomVals

RandomNums r = SetRandomVals(low, high);

The prototype I had tried was

SetRandomVals(int low,int high); 

As for my professor, I may not edit the Main.c file.

EDIT: after adding the function prototype my new error is that I have an undefined reference after it had already stated I had an implicit declaration.

/tmp/ccOhjlhD.o: In function `main':
main.c:(.text 0x63): undefined reference to `SetRandomVals'
collect2: error: ld returned 1 exit status

CodePudding user response:

The prototype shall be the same as the function header in the definition: struct RandomNums setRandomVals(int low,int high).

and it should be declared before any caller calls the function.

CodePudding user response:

The return type needs to be included in the declaration.

And to do that, you will need to include the struct definition in the .h.

struct RandomNums { ... };

struct RandomNums setRandomVals(int low, int high);

By the way, you can avoid using the word struct everywhere by using a (possibly-anonymous) struct.

typedef struct { ... } RandomNums;

RandomNums setRandomVals(int low, int high);
  • Related