简体   繁体   中英

How can i run multiple files in C (visual studio code)?

I want to to run a simple program, using vs code, which includes three files: main.c item.c item.h.

I understand that I there is a way to link things together, but I don't know how. Can you explain me how to do it?

I've tried also to add the extension to make a project, but I didn't understand how to.

Here's the code:

main.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "item.h"


int main () {

  int a = 2;
  int b = 3;
  int res;
  res = prod(a,b);

  printf("%d ", res);

  return 0;
}

item.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "item.h"

int prod(int a, int b) {
    return a*b;
}

item.h

#ifndef ITEM_H
#define ITEM_H

int prod(int a, int b);

#endif

I don't know if you are using Windows or Linux or Mac, I'm going to explain it for Linux but the method is similar for the others.

First of you go on VS Code, then you click on new file and rename it "makefile", then you write this:

link: item.o main.o 
     gcc item.o main.o -o programName

main.o:
     gcc -c main.c

item.o: 
     gcc -c item.c

clear:
     rm -f item.o main.o programName //this one is to delete files faster

Once you wrote the makefile you write in the terminal the command make and you get the executable file for your program.

However in item.c you aren't using any of the library you included, you only need to include item.h ; last thing, I don't know why you are doing the #ifndef thing but it seems a waste.

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