将问题与导出的函数相关联

Linking issues with an exported function

本文关键字:函数 关联 问题      更新时间:2023-10-16

我试图创建一个基本的hello-world程序,但在一些链接问题上失败了。

程序中.cpp

#include <iostream>
#include <string>
#include "scanner.h"
using namespace std;
int main() {
  string result = createScanner();
  cout << result << endl;
  return 0;
}

在扫描仪.h 中

#include <string>
using namespace std;
string createScanner();

在扫描仪.cpp 中

#include <scanner.h>
#include <string>
using namespace std;
string createScanner() {
    return "hello world";
}

使用此CLI方法:

clang++ -O3 -std=c++11 -stdlib=libc++  -I./includes/ -I./compiler/  compiler/program.cpp  -o hej

我得到了这个错误:

Undefined symbols for architecture x86_64:
  "createScanner()", referenced from:
      _main in program-45fd7b.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [all] Error 1

选项1:将scanner.cpp添加到命令行

clang++ -O3 -std=c++11 -stdlib=libc++  -I./includes/ -I./compiler/  compiler/program.cpp compiler/scanner.cpp -o hej

选项2:将编译步骤与链接步骤分离

clang++ -c -O3 -std=c++11 -stdlib=libc++  -I./includes/ -I./compiler/  compiler/program.cpp -o compiler/program.o
clang++ -c -O3 -std=c++11 -stdlib=libc++  -I./includes/ -I./compiler/  compiler/scanner.cpp -o compiler/scanner.o
clang++ -O3 -std=c++11 -stdlib=libc++  compiler/program.o compiler/scanner.o -o hej

选项3:使用Makefile

Makefile:的内容

CXX=clang++
CXXFLAGS= -O3 -std=c++11 -stdlib=libc++ -Wall -I./includes/ -I./compiler/ 
hej: compiler/program.o compiler/scanner.o
    clang++ -O3 -std=c++11 -stdlib=libc++ -o $@ $^

然后运行:

make