首页 > 解决方案 > 如何在 C++ 中包含头文件和实现文件?

问题描述

我正在学习 c++,讲师制作了一个关于如何在多个文件中制作类和函数的视频。

我有 3 个简单的 c++ 文件,分别称为“main.cpp”、“something.h”和“something.cpp”,它们都在同一个目录中,没有其他文件。(他们在下面)

问题是链接器正在抛出错误消息,我真的不知道为什么。(也许我只是错过了一些非常明显的东西)

// main.cpp 

#include <iostream>
#include "something.h"

int main(){
    int a{2}, b{2};
    std::cout << add(a,b) << std::endl;

    int arr[5] {1,2,4,8,16};

    print_arr(arr, 5);

    std::cout << "Hello, world\n"; 
    return 0;
}
// something.h
#ifndef _SOMETHING_H_
#define _SOMETHING_H_ 

int add(int a, int b);
void print_arr(int* arr, unsigned int size);

#endif // _SOMETHING_H_
// something.cpp
#include "something.h"
#include <iostream>
int add(int a, int b){
     return a+b; 
}

void print_arr(int* arr, unsigned int size){
     std::cout << "{ ";
     for (int i = 0; i < size; i++)
          std::cout << arr << ' ';
     std::cout << '}';
}

错误:

Undefined symbols for architecture x86_64:
  "add(int, int)", referenced from:
      _main in main-06aa98.o
  "print_arr(int*, unsigned int)", referenced from:
      _main in main-06aa98.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

标签: c++linker-errorsheader-files

解决方案


最简单的,clang++ -Wall -g something.cpp main.cpp -o main.

您也可以something.cpp先编译以创建something.o...

clang++ -Wall -g -c something.cpp

...然后在编译时指定链接main.cpp

clang++ -Wall -g main.cpp something.o

最后一种方法可以更好地扩展,就好像您只更改main.cpp您可以只执行第二步而无需重新编译something.o.


推荐阅读