Home > OS >  I'm having troubles trying to compile this C program with g ? (Using a zsh terminal, macOS o
I'm having troubles trying to compile this C program with g ? (Using a zsh terminal, macOS o

Time:06-13

I'm using a macOS operating system & within the terminal I have installed g , when trying to compile my C Program File, which has separate compilation; the following error message occurs:

main.cpp:3:10: fatal error: 'Item.h' file not found #include "Item.h" ^~~~~~~~ 1 error generated. [~/Desktop/C Practice, with the following command: g main.cpp -std=c 11

I'm assuming I have to compile the other programs. One is a header program which has a declared class, and in another .cpp program, it defines the class in the header program. Sorry if this explanation is poorly written or not that understanding, I'm having big troubles continuing my programming journey so if there's something you can't understand in this post please leave a comment on this post & I will do my best to explain the subject to you, thanks.

CodePudding user response:

If Item.h is not in your current directory, you will need to specify the directory containing it as an include directory in the g command. For example, if your folder structure is this:

.
├── headers
│   └── Item.h
├── items.cpp
└── main.cpp

Then your g command(s) should be

g   -o main.o -std=c  11 -Iheaders -c main.cpp
g   -o items.o -std=c  11 -Iheaders -c items.cpp
g   -o program items.o main.o

Note that with separate translation units (cpp files), you need to compile each one to an object file first (.o file, that's what the -c option does), and then link them together with the last command.

Alternatively, with a small number of translation units, you can get away with compiling and linking them in one step:

g   -o program -Iheaders -std=c  11 main.cpp items.cpp

I would definitely recommend setting up a Makefile or some other form of build system if you will have many translation units.

  • Related