简体   繁体   中英

Visual studio code C external files

Whenever I try to use extern variable in another.c file of the same folder or if I want to use external function I get an error: ld returned 1 exit status

While if I am trying to use eclipse for the same example it works with no errors

Before you can use a (extern) variable, you have to declare it first and then define it.

Example

Declare the var in a header file, eg foo.h :

extern int my_extern_var; //declaration (extern)

Define it in a source file, eg foo.c :

#include "foo.h"   //include the declaration
int my_extern_var; //definition

Then use it in any other source file(s):
(even if foo is a library and get linked to the program below)

#include <stdio.h>
#include "foo.h" //include the declaration

int main() 
{
    my_extern_var = 42; //usage of 'global' var
    printf("%d\n", my_extern_var);

    return 0;
}

Reference:

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