Gcc uses sqrt without including math.h - c

Anyone knows why this c program compiles and uses the sqrt of math.h?
this would output 2.236068
main.c
#include <stdio.h>
#include "math_utils.h"
int main(void){
printf("%f\n", sqrt(5));
return 0;
}
math_utils.h
#ifndef MATH_UTILS_Hs
#define MATH_UTILS_Hs
double sqrt(double number){
return number + 5;
}
#endif // MATH_UTILS_Hs
I am currently using mingw GCC on windows

gcc performs an optimization where it expects standard library functions to behave like the standard says to turn calls into the C standard library into more efficient machine code. For example, it's likely that gcc emits a single fsqrt instruction for your sqrt() call, never calling your custom sqrt() at all.
You can turn off this behaviour by supplying -fno-builtin to turn this optimization off for all recognized functions or by supplying -fno-builtin-function to turn off this optimization for function only. For example, -fno-builtin-sqrt would make gcc honour your non-standard sqrt().

Related

Why is no warning given for the wrong use of __attribute__((pure)) in GCC?

I am trying to understand pure functions, and have been reading through the Wikipedia article on that topic. I wrote the minimal sample program as follows:
#include <stdio.h>
static int a = 1;
static __attribute__((pure)) int pure_function(int x, int y)
{
return x + y;
}
static __attribute__((pure)) int impure_function(int x, int y)
{
a++;
return x + y;
}
int main(void)
{
printf("pure_function(0, 0) = %d\n", pure_function(0, 0));
printf("impure_function(0, 0) = %d\n", impure_function(0, 0));
return 0;
}
I compiled this program with gcc -O2 -Wall -Wextra, expecting that an error, or at least a warning, should have been issued for decorating impure_function() with __attribute__((pure)). However, I received no warnings or errors, and the program also ran without issues.
Isn't marking impure_function() with __attribute__((pure)) incorrect? If so, why does it compile without any errors or warnings, even with the -Wextra and -Wall flags?
Thanks in advance!
Doing this is incorrect and you are responsible for using the attribute correctly.
Look at this example:
static __attribute__((pure)) int impure_function(int x, int y)
{
extern int a;
a++;
return x + y;
}
void caller()
{
impure_function(1, 1);
}
Code generated by GCC (with -O1) for the function caller is:
caller():
ret
As you can see, the impure_function call was completely removed because compiler treats it as "pure".
GCC can mark the function as "pure" internally automatically if it sees its definition:
static __attribute__((noinline)) int pure_function(int x, int y)
{
return x + y;
}
void caller()
{
pure_function(1, 1);
}
Generated code:
caller():
ret
So there is no point in using this attribute on functions that are visible to the compiler. It is supposed to be used when definition is not available, for example when function is defined in another DLL. That means that when it is used in a proper place the compiler won't be able to perform a sanity check anyway. Implementing a warning thus is not very useful (although not meaningless).
I don't think there is anything stopping GCC developers from implementing such warning, except time that must be spend.
A pure function is a hint for the optimizing compiler. Probably, gcc don't care about pure functions when you pass just -O0 to it (the default optimizations). So if f is pure (and defined outside of your translation unit, e.g. in some outside library), the GCC compiler might optimize y = f(x) + f(x); into something like
{
int tmp = f(x); /// tmp is a fresh variable, not appearing elsewhere
y = tmp + tmp;
}
but if f is not pure (which is the usual case: think of f calling printf or malloc), such an optimization is forbidden.
Standard math functions like sin or sqrt are pure (except for IEEE rounding mode craziness, see http://floating-point-gui.de/ and Fluctuat for more), and they are complex enough to compute to make such optimizations worthwhile.
You might compile your code with gcc -O2 -Wall -fdump-tree-all to guess what is happening inside the compiler. You could add the -fverbose-asm -S flags to get a generated *.s assembler file.
You could also read the Bismon draft report (notably its section ยง1.4). It might give some intuitions related to your question.
In your particular case, I am guessing that gcc is inlining your calls; and then purity matters less.
If you have time to spend, you might consider writing your own GCC plugin to make such a warning. You'll spend months in writing it! These old slides might still be useful to you, even if the details are obsolete.
At the theoretical level, be aware of Rice's theorem. A consequence of it is that perfect optimization of pure functions is probably impossible.
Be aware of the GCC Resource Center, located in Bombay.

Force gcc to use syscalls

So I am currently learning assembly language (AT&T syntax). We all know that gcc has an option to generate assembly code from C code with -S argument. Now, I would like to look at some code, how it looks in assembly. The problem is, on laboratories we compile it with as+ld, and as for now, we cannot use C libraries. So for example we cannot use printf. We should do it by syscalls (32 bit is enough). And now I have this code in C:
#include <stdio.h>
int main()
{
int a = 5;
int b = 3;
int c = a + b;
printf("%d", c);
return 0;
}
This is simple code, so I know how it will look with syscalls. But if I have some more complicated code, I don't want to mess around and replace every call printf and modify other registers, cuz gcc generated code for printf, and I should have it with syscalls. So can I somehow make gcc generate assembly code with syscalls (for example for I/O (console, files)), not with C libs?
Under Linux there exist the macro family _syscallX to generate a syscall where the X names the number of parameters. It is marked as obsolete, but IMHO still working. E.g., the following code should work (not tested here):
_syscall3(int,syswrite,int,handle,char*,str,int len);
// ---
char str[]="Hello, world!\n";
// file handle 1 is stdout
syswrite(1,str,14);

Matlab error compiling C files with mex

i'm trying to compile a program for image deblurring.
I try to run
mex apply_blur_kernel_mex.c
where the file apply_blur_kernel_mex.c have the following code
#include <mex.h>
#include <stdlib.h>
#include <math.h>
#include <matrix.h>
#include "ow_homography.h"
...
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
...
compute_homography_matrix(Ksharp, &theta_list[k*3], invKblurry, H);
...
}
The problem is in the function compute_homography_matrix that is in another file ow_homography.h
#ifndef OW_HOMOGRAPHY_H
#define OW_HOMOGRAPHY_H
#include "ow_mat3.h"
INLINE void compute_homography_matrix(const double *Ksharp, const double *theta, const double *invKblurry, double *H) {
double R[9];
/* Compute homography */
cp3(invKblurry,H);
rot3(theta[0],theta[1],theta[2],R);
mmip3(R,H);
mmip3(Ksharp,H);
}
This last operations (cp3, rot3...) are in another file ow_mat3.h that contains all the operations for the program.
So when i try to call
mex apply_blur_kernel_mex.c
i have the following problem:
Error using mex
Undefined symbols for architecture x86_64:
"_compute_homography_matrix", referenced from:
mexFunction in apply_blur_kernel_mex.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Any suggestions to solve this problem?
Thank you all.
http://clang.llvm.org/compatibility.html#inline
C compatibility C99 inline functions
By default, Clang builds C code in GNU C11 mode, so it uses standard
C99 semantics for the inline keyword. These semantics are different
from those in GNU C89 mode, which is the default mode in versions of
GCC prior to 5.0. For example, consider the following code:
inline int add(int i, int j) { return i + j; }
int main() { int i = add(4, 5); return i; }
In C99, inline means that a function's definition is provided only for
inlining, and that there is another definition (without inline)
somewhere else in the program. That means that this program is
incomplete, because if add isn't inlined (for example, when compiling
without optimization), then main will have an unresolved reference to
that other definition. Therefore we'll get a (correct) link-time error
like this:
Undefined symbols: "_add", referenced from:
_main in cc-y1jXIr.o
By contrast, GNU C89 mode (used by default in older versions of GCC)
is the C89 standard plus a lot of extensions. C89 doesn't have an
inline keyword, but GCC recognizes it as an extension and just treats
it as a hint to the optimizer.
There are several ways to fix this problem:
1) Change add to a static inline function. This is usually the right solution if only one translation unit needs to use the function.
static inline functions are always resolved within the translation
unit, so you won't have to add a non-inline definition of the function
elsewhere in your program.
2) Remove the inline keyword from this definition of add. The inline keyword is not required for a function to be inlined, nor does it
guarantee that it will be. Some compilers ignore it completely. Clang
treats it as a mild suggestion from the programmer.
3) Provide an external (non-inline) definition of add somewhere else in your program. The two definitions must be equivalent!
4)Compile in the GNU C89 dialect by adding -std=gnu89 to the set of Clang options. This option is only recommended if the program source
cannot be changed or if the program also relies on additional
C89-specific behavior that cannot be changed.
All of this only applies to C code; the meaning of inline in C++ is
very different from its meaning in either GNU89 or C99.

clang issue: inline function inside another function body in C

It is challenging to port from Linux to OS/X. I have an inline function embedded inside another function body. On Linux, gcc happily compiled the code, but on OS/X, clang reports error.
Here is the code snippet,
$ cat inline.c
void func() {
inline int max(int a, int b) { return (a>b) ? a : b; }
int c = max(11,22);
}
On Linux, everything is fine,
Linux $ gcc -c inline.c
Linux $$ gcc --version
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
However, clang on OS/X complains,
OSX $ cc -c inline.c
inline.c:2:38: error: function definition is not allowed here
inline int max(int a, int b) { return (a>b) ? a : b; }
^
inline.c:3:17: warning: implicit declaration of function 'max' is invalid in C99
[-Wimplicit-function-declaration]
int c = max(11,22);
^
1 warning and 1 error generated.
OSX $ cc --version
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0
Is this a gcc "feature" or there is a clang flag to enable this capability?
GCC extensions not implemented yet
clang does not support nested functions; this is a complex feature which is infrequently used, so it is unlikely to be implemented anytime soon.
Just move the max out the function and make it static.
Here, "inline" means "inline substitution", rather than "inline definition".
According to N1570:
6 A function declared with an inline function specifier is an inline
function. Making a function an inline function suggests that calls to
the function be as fast as possible.138) The extent to
which such suggestions are effective is
implementation-defined.139)
138) By using, for example, an alternative to the usual function
call mechanism, such as ''inline substitution''. ...
And you shouldn't define another function in a function definition. Also, use static inline instead of inline would make your life easier.

glibc - force function call (no inline expansion)

I have a question regarding glibc function calls. Is there a flag to tell gcc not to inline a certain glibc function, e.g. memcpy?
I've tried -fno-builtin-memcpy and other flags, but they didn't work. The goal is that the actual glibc memcpy function is called and no inlined code (since the glibc version at compile time differs from the one at runtime). It's for testing purposes only. Normally I wan't do that.
Any solutions?
UPDATE:
Just to make it clearer: In the past memcpy works even with overlapping areas. This has changed meanwhile and I can see this changes when compiling with different glibc versions. So now I want to test if my old code (using memcpy where memmove should have been used) works correct or not on a system with a newer glibc (e.g. 2.14). But to do that, I have to make sure, that the new memcpy is called and no inlined code.
Best regards
This may not be exactly what you're looking for, but it seems to force gcc to generate an indirect call to memcpy():
#include <stdio.h>
#include <string.h>
#include <time.h>
// void *memcpy(void *dest, const void *src, size_t n)
unsigned int x = 0xdeadbeef;
unsigned int y;
int main(void) {
void *(*memcpy_ptr)(void *, const void *, size_t) = memcpy;
if (time(NULL) == 1) {
memcpy_ptr = NULL;
}
memcpy_ptr(&y, &x, sizeof y);
printf("y = 0x%x\n", y);
return 0;
}
The generated assembly (gcc, Ubuntu, x86) includes a call *%edx instruction.
Without the if (time(NULL) == 1) test (which should never succeed, but the compiler doesn't know that), gcc -O3 is clever enough to recognize that the indirect call always calls memcpy(), which can then be replaced by a movl instruction.
Note that the compiler could recognize that if memcpy_ptr == NULL then the behavior is undefined, and again replace the indirect call with a direct call, and then with a movl instruction. gcc 4.5.2 with -O3 doesn't appear to be that clever. If a later version of gcc is, you could replace the memcpy_ptr = NULL with an assignment of some actual function that behaves differently than memcpy().
In theory:
gcc -fno-inline -fno-builtin-inline ...
But then you said -fno-builtin-memcpy didn't stop the compiler from inlining it, so there's no obvious reason why this should work any better.
#undef memcpy
#define mempcy your_memcpy_replacement
Somewhere at the top but after #include obviously
And mark your_memcpy_replacement as attribute((noinline))

Resources