I’m writing a linux kernel module that makes use of the exported symbol open_exec
struct file *open_exec(const char *name)
It returns a pointer, and I can check for an error with the IS_ERR macro:
if (IS_ERR(file))
return file;
During compile time, I get this warning:
warning: return makes integer from pointer without a cast
This is because my function here returns an integer. If I try to cast it:
return (int) file;
I don’t get a warning on my 32bit machine, but I do on my 64bit machine:
warning: cast from pointer to integer of different size
This is because the sizeof of an int and a pointer are the same on 32bit, but they differ on a 64bit machine.
Casting it or not, the code appears to work. I’d just like to get rid of the warning.
How do I properly cast a pointer to an integer and get the value I expect, while not getting a compiler warning? The value I expect is essentially an integer listed in include/asm-generic/errno-base.h of the linux kernel code base.
Since I’m only looking at the pointer as if it was an integer in the case where IS_ERR() is true, I can be sure that it does in-fact only hold an integer value.
The
PTR_ERR()macro inlinux/err.h, which is whereIS_ERR()is also defined, converts a pointer that’s really an error code into the appropriate type (along).You should use something like:
Search for existing uses of
PTR_ERR()in the source and you’ll see this is a common pattern.It might be appropriate for your function to return a
longrather than anint– but all error codes should be representable in anint.