Search code examples
c++header-files

c++ include header get failed


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!


Solution

  • 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.