将问题与导出的函数链接起来

时间:2015-03-24 15:01:16

标签: c++

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

在program.cpp中

#include <iostream>
#include <string>
#include "scanner.h"

using namespace std;

int main() {
  string result = createScanner();
  cout << result << endl;
  return 0;
}
在scan.h中

#include <string>

using namespace std;

string createScanner();
扫描仪中的

#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 个答案:

答案 0 :(得分: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