Domanda

Please help? I'm at a bit of a loss here.

main.c:

int main(){
    double x = 12.345;
    set_alpha(x);
    double y = get_alpha();
    printf("%f\n", y);
    return 0;
}

block.c:

double alpha;
void set_alpha(double a){
    alpha = a;
    printf("%f\n", alpha);
}
double get_alpha(){
    return alpha;
}

When running gcc block.c main.c, I get

12.345000
183898224.000000

, where the latter number changes at random. What's going on and how do I fix my faux getter/setter functions?

È stato utile?

Soluzione

If you don't have prototypes for get and set_alpha then the compiler doesn't know what their parameters and return values are. Each source file is compiled independently. If the prototypes aren't listed in main.c then the compiler has to guess at the function signatures. It wrongly guesses that everything's an int, as in int set_alpha(int a) and int get_alpha(). Oops!

The fix:

void set_alpha(double a);
double get_alpha();

int main() {
    ...
}

The best thing to do is to create a separate header file block.h and put the prototypes there. Also to make sure to enable all your compiler's warnings (e.g. gcc -Wall) so you don't get bit by this again.

block.h

#ifndef BLOCK_H
#define BLOCK_H 

void set_alpha(double a);
double get_alpha();

#endif

main.c

#include "block.h"

int main() {
    ...
}

block.c

#include "block.h"

... 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top