Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top