Answer the question
In order to leave comments, you need to log in
Compiling a C program?
Hello!
There is a compiler gcc version 4.4.3 (Ubuntu) and two files:
~/test/main.c
#include <stdio.h>
int main() {
int x = next(6);
printf("%d\n", x);
return 0;
}
int next(int a) {
return a + 1;
}
gcc main.c next.c -o test
Answer the question
In order to leave comments, you need to log in
I advise you to replace "int next(int a)" with "double next(double a)". Then it will be more fun.
If you compile with -Wall -Werror, gcc will crash and won't build anything. If without these keys, it will warn that the next function was considered by default to return an int. But when it actually returns double, there may be some unexpected consequences (or maybe not).
The function declaration is optional. In this case, the compiler assumes that the function has any number of arguments and returns an int. Prototype: int func();
During the linking process, the function was found in next.o, which means everything is fine%)
>Tell me how this happens without a header file?
When the compiler makes .o files, there the name of the next function will be without mangling, that is, simply _next
And when ld (aka the linker) collects from two .o into one executable file, everything will be OK.
And if you do it in C ++ (aka g ++), this trick will not work, because there will be name mangling and in one .o file it will turn out like [email protected] and in another [email protected] and the linker will not collect it. Although in C ++, it seems that the compiler will also swear that he met the girl with a crescent moon , a function without a header.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question