Home > OS >  how to compile header files in c in visual studio code
how to compile header files in c in visual studio code

Time:09-22

I creating a program in c language and i using the Visual Studio Code for the first time, my functions in the header files don't function. This is my code in main:

#include <stdio.h>
#include "PilhaDinamica.h"
#include "PilhaEstatica.h"

int main()
{
    Pilha *p = criaPilha();
    
    return 0;
}

And this is my .h file:

#ifndef PILHADINAMICA_H_INCLUDED
#define PILHADINAMICA_H_INCLUDED


typedef struct Nodo{
    char info;
    struct Nodo*prox;
} nodo;

typedef struct {
    nodo * Topo;
} Pilha;

Pilha * criaPilha();
int pilha_vazia(Pilha *p);
void push(Pilha *p, char times);
char pop(Pilha *p);
#endif

This is my file with the functions:

#include "PilhaDinamica.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
Pilha *criaPilha()
{
    Pilha *p = (Pilha*) malloc(sizeof(Pilha));
    p->Topo = NULL;
    return p;
}

And this is shown in my output: "...\AppData\Local\Temp\ccmjk1nS.o:main.c:(.text 0xf): undefined reference to `criaPilha' collect2.exe: error: ld returned 1 exit status"

what can i do to make it compile correctly?

CodePudding user response:

As a general rule of thumb, header files (*.h) contains declarations (type, variable and function declarations) and source files (*.c) the definitions of those declarations.

At the compilation step, only source files will be compiled (because the definitions are there). A program or library creation is a 2 (actually more, like preprocessing and more but for simplicity we keep it at 2) step process:

  1. creating object files

e.g. gcc -c -o object_file_name.o source_file_name.c

  1. link those object files into an executable or static/shared library

e.g. gcc -o program_or_library_name object_file_1.o object_file_2.o ...

So, in your case you have to call the compiler two times for your source files (with the -c flag) and once to link those created object files into an executable.

Note: If you're using a different compiler other than gcc, have a look at the documentation on how to create object files and link them together.

  • Related