How do I link object files in C? Fails with “Undefined symbols for architecture x86_64”

前端 未结 5 451
误落风尘
误落风尘 2020-12-02 08:53

So I\'m trying trying to use a function defined in another C (file1.c) file in my file (file2.c). I\'m including the header of file1 (file1.h) in order to do this.

H

5条回答
  •  孤街浪徒
    2020-12-02 09:40

    Add foo1.c , foo2.c , foo3.c and makefile in one folder the type make in bash

    if you do not want to use the makefile, you can run the command

    gcc -c foo1.c foo2.c foo3.c
    

    then

    gcc -o output foo1.o foo2.o foo3.o
    

    foo1.c

    #include 
    #include 
    
    void funk1();
    
    void funk1() {
        printf ("\nfunk1\n");
    }
    
    
    int main(void) {
    
        char *arg2;
        size_t nbytes = 100;
    
        while ( 1 ) {
    
            printf ("\nargv2 = %s\n" , arg2);
            printf ("\n:> ");
            getline (&arg2 , &nbytes , stdin);
            if( strcmp (arg2 , "1\n") == 0 ) {
                funk1 ();
            } else if( strcmp (arg2 , "2\n") == 0 ) {
                funk2 ();
            } else if( strcmp (arg2 , "3\n") == 0 ) {
                funk3 ();
            } else if( strcmp (arg2 , "4\n") == 0 ) {
                funk4 ();
            } else {
                funk5 ();
            }
        }
    }
    

    foo2.c

    #include 
    void funk2(){
        printf("\nfunk2\n");
    }
    void funk3(){
        printf("\nfunk3\n");
    }
    

    foo3.c

    #include 
    
    void funk4(){
        printf("\nfunk4\n");
    }
    void funk5(){
        printf("\nfunk5\n");
    }
    

    makefile

    outputTest: foo1.o foo2.o foo3.o
        gcc -o output foo1.o foo2.o foo3.o
        make removeO
    
    outputTest.o: foo1.c foo2.c foo3.c
        gcc -c foo1.c foo2.c foo3.c
    
    clean:
        rm -f *.o output
    
    removeO:
        rm -f *.o
    

提交回复
热议问题