C header issue: #include and “undefined reference”

前端 未结 5 596
无人共我
无人共我 2021-02-03 22:14

Alright, I\'ve been trying to work with this for the longest time, and I simply can\'t seem to get it to work right. I have three files, main.c, hello_world.c

相关标签:
5条回答
  • 2021-02-03 22:34
    gcc main.c hello_world.c -o main
    

    Also, always use header guards:

    #ifndef HELLO_WORLD_H
    #define HELLO_WORLD_H
    
    /* header file contents go here */
    
    #endif /* HELLO_WORLD_H */
    
    0 讨论(0)
  • 2021-02-03 22:35

    You should link object file compled from your second .c file hello_world.c with your main.o

    try this

    cc -c main.c
    cc -c hello_world.c
    cc *.o -o hello_world
    
    0 讨论(0)
  • 2021-02-03 22:39

    You are not including hello_world.c in compilation.

       gcc hello_world.c main.c   -o main
    
    0 讨论(0)
  • 2021-02-03 22:40

    Ya it seems you have forgotten to link hello_world.c. I will be gcc hello_world.c main.c -o main. If the number of files are less we can use this approach but in larger projects better to use Make files or some compilation scripts.

    0 讨论(0)
  • 2021-02-03 22:43

    You are not linking against hello_world.c.

    An easy way to do this is to run this compilation command:

    cc -o main main.c hello_world.c

    More complicated projects often use build scripts or make files that separate the compilation and linking commands, but the above command (combining both steps) should do fine for small projects.

    0 讨论(0)
提交回复
热议问题