1

recently I've started learning c++. When I tried to write my header file, I got include error. Here is my code: First is the header file(header.h)

#pragma once void print(int); 

and then is its cpp file(header.cpp)

#include "header.h" #include <iostream> using namespace std; void print(int x){ cout << x << endl; } 

and finally my main cpp program(main.cpp)

#include <iostream> #include "./header.h" using namespace std; int main(){ int x = 123; print(x); } 

Here is the error, I can't figure out what it's saying orz

cd "/Users/yianchen/Desktop/cpp practice/" && g++ main.cpp -o main && "/Users/yianchen/Desktop/cpp practice/"main Undefined symbols for architecture x86_64: "print(int)", referenced from: _main in main-90c620.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have searched for some solution, when I use

#include "header.cpp" 

It works fine, but I see guys unrecommended using #include some_file.cpp

By the way, I use visual studio code and use code runner. Thanks!

2 Answers 2

2

The easiest solution would be to do something like the following

g++ header.cpp main.cpp 

This will make sure that the function defined in header.cpp is compiled together with the code that uses it.

Sign up to request clarification or add additional context in comments.

Comments

2

Normal usage would be to compile header.cpp, not to include it in another .cpp source. Then the linker will put the pieces together.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.