简体   繁体   中英

Why is that with Visual Studio code the function declaration in header file not required?

I am using MSVC. Earlier I used Code Blocks where to share functions across files one need to put the declaration of that shared function in a header file. But with MSVC we don't need to do that, why? Is it because MSVC does that work for us behind the scenes? Also now I have to specify mutiple.c files that are to be compiled in the tasks.json file.

main.c:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    add(2,5);
    return 0;
}

utilities.c:

#include <stdio.h>

void add(int a, int b) {
    printf("sum: %d\n", a+b);
}

Output: With MSVC: sum: 7

With Code Blocks: implicit declaration of function 'add' undefined reference to function 'add'

Why such difference in outputs?

Let's turn chaos into order:

  1. implicit declaration of function 'func'

This is a compiler warning, telling you that the exact prototype of function func is unknown at the time of the compilation of this specific source file into an object code.

The compiler "lets you off" with a warning, assuming that the aforementioned function is implemented in some other source file, and that the linker will later be able to link between the object code of the current source file, and the object code of that other source file.

  1. undefined reference to function 'func'

This is a linker error, telling you that the assumption previously made by the compiler was... well, you know what they say about assumptions...

Anyway, as you may have understood by know, turning your source code into an executable image requires these two steps, executed sequentially (ie, one after the other, and not in parallel):

  1. Compilation of each source file into an object code
  2. Linkage of all the object codes into an executable image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM