Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to compile any .c file in isolation (that is, without a main?)

Tags:

c++

c

I currently have a "library-like" .c file (that'll be shown below). I have 2 questions about it:

  1. If I want to see if it compiles well for itself, how can I do it? If I try to gcc it, it will always give a "no main" error, which makes sense, but raises the problem of knowing if a given .c file will compile well or not in "isolation". Can I safely conclude that if the only error raised by the compiler is the "no main" one, my file is fine? An example of where compiling .c files in isolation could be nice would be to determine which includes are in excess, in here.

  2. Is there a point in a simple file like this to define a header with its method / struct declarations and then have such tiny .c file with the 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

Thanks

like image 842
devoured elysium Avatar asked Nov 17 '10 01:11

devoured elysium


1 Answers

To compile it without linking (doesn't require a main entry point):

cc -c file.c -o file.o

Even for a small file that defines routines that will be called from other source files you still want a header file. The header file is how the compiler knows the interface to the routines before the linker ties it all together. If you don't have declarations for functions that are external then the compiler has to make assumptions (usually wrong) about the data types of the parameters. You can declare the functions in every source file where they are used, but the point of header files is so that you just do it once in the header file.

like image 140
kanaka Avatar answered Sep 28 '22 06:09

kanaka