It is possible to compile any .c file separately (i.e. without the main?)

I currently have a .c library file (this will be shown below). I have 2 questions:

  • If I want it to compile well for myself, how can I do this? If I try to gcc it, it will always give a “no main” error, which makes sense, but causes a problem with understanding whether a given .c file will compile well or not in “isolation”. Can I conclude with confidence that if the only error caused by the compiler is “no main”, is my file ok? An example of where compiling .c files individually can be enjoyable would be to determine which ones are in excess here.

  • Is there a point in a simple file like this to define a header with its method / struct declarations, and then have such a tiny .c file with code implementation in it?

    #ifndef SEMAFOROS
    #define SEMAFOROS
    
    
    #include <signal.h>
    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <semaphore.h>
    
    
    typedef struct {
        sem_t* id;
        char* nome;
    } Semaforo;
    
    
    inline void lock(Semaforo* semaforo) {
        sem_wait(semaforo->id);
    }
    
    
    inline void unlock(Semaforo* semaforo) {
        sem_post(semaforo->id);
    }
    
    
    Semaforo* criarSemaforo(char* nome) {
        Semaforo* semaforo = (Semaforo*)malloc(sizeof(Semaforo));
        semaforo->id = sem_open(nome, O_CREAT, 0xFFFFFFF, 1);
        semaforo->nome = nome;
    }
    
    
    void destruirSemaforo(Semaforo* semaforo) {
        sem_close(semaforo->id);
        sem_unlink(semaforo->nome);
    
    
    
    free(semaforo);
    
    } #endif >

thank

+5
source share
3 answers

Compile it without binding (no main entry point required):

cc -c file.c -o file.o

, , , . - , , . , ( , ) . , , , .

+10

-c gcc , , .c .o.

"". .c, - . .h .

+3

, !

2, , .

, file.c:

int number_of_chickens;

file2.c , , int, file.c:

extern double number_of_chickens;
double count_chickens() {
    return number_of_chickens;
}

void add_to_chickens(double how_many) {
    number_of_chickens += how_many;
}

. number_of_chickens , 4- int file.c, 8- double file2.c.

count_chickens, ( 32 int number_of_chickens, 32 undefined - , number_of_chickens ).

, add_to_chickens(1) file2.c, 8 4 , , , , ( , ).

, . , 3 .

+2
source

All Articles