-1

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
Hogstrom
  • 3,581
  • 2
  • 9
  • 25
  • I'm assuming visual studio code uses a json or some makefile, where is that file? – Irelia Mar 21 '22 at 12:26
  • Which extension are you using? – Irelia Mar 21 '22 at 12:30
  • https://iraspa.org/blog/visual-studio-code-c-cpp-fortran-with-multiple-source-files/ -> is that helpful – Vineesh Vijayan Mar 21 '22 at 12:31
  • Do you get any error message when compiling ? –  Mar 21 '22 at 13:02
  • 2
    If you use multiple C/C++ files you should use a build tool CMake/Make/MSBuild/.... – rioV8 Mar 21 '22 at 13:10
  • @YvesDaoust , yes, i should have mentioned it. I get this undefined reference to `prod' collect2.exe: error: ld returned 1 exit status – GamblingMan Mar 21 '22 at 13:13
  • Does this answer your question? [VS Code will not build c++ programs with multiple .ccp source files](https://stackoverflow.com/questions/47665886/vs-code-will-not-build-c-programs-with-multiple-ccp-source-files) – 273K Mar 03 '23 at 20:18

1 Answers1

0

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.

Antonino
  • 26
  • 4