문제

So I'm working through this chapter of a sweet modern OpenGL tutorial, and in part of the code I assign a void pointer variable to the return value of a void * function from a second file. I got this error from gcc: initialization makes pointer from integer without a cast. As a test, I tried merging the two files and compiling again. This time, with the function in the same file as where it's called, I get no error.

I was able to reproduce this with three minimal files:

file1.c

void main() {
    void *newval = foo();
}

file2.c

#include <stdlib.h>

void *foo() {
    void *val;
    val = malloc(10);
    return val;
}

file3.c

#include <stdlib.h>

void *foo() {
    void *val;
    val = malloc(10);
    return val;
}

void main() {
    void *newval = foo();
}

file3.c is just the first two combined. My question is why when I compile one way I get an error, and the other way I get none:

$gcc file1.c file2.c
file1.c: In function ‘main’: file1.c:2:17: warning: initialization makes pointer from integer without a cast [enabled by default]
$gcc file3.c
$

I thought that the file1.c + file2.c combo was identical to file3.c. What am I missing?

도움이 되었습니까?

해결책

In your file1.c, it seems the declaration of void *foo() is missing. You can either include the header file containing this declaration or add line void *foo() on top of file1.c.

When compiler finds symbol foo followed by ( in main file, and there was no declaration, it assumes foo accepts any number of arguments and returns an int. So you see the warning that int is being converted to a pointer.

But in file file3.c, symbol foo is known as it is a defined function before its first usage so compiler knows that foo returns a pointer and thus no warning.

다른 팁

You need to declare the foo() function so that compiler knows what it is when it compiles file1.c.

Create file2.h and add in it

void *foo();

add include it in file.c

#include "file2.h"

Without declaration, the compiler assumes all unknown functions as returning int, but as your function returns void * and you are assigning it to void *, its trying to assign int to void * and hence you are getting that warning.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top