c++ - 编译斯坦福 C++ 库

标签 c++ compilation compiler-errors ld

http://www.stanford.edu/class/cs106b/assignments/Assignment1-linux.zip

我正在为即将到来的 Coursera 类(class)自学这项作业。我在 0-Warmup 文件夹中修改了 Warmup.cpp 如下:

#include <iostream>
#include <string>
#include "StanfordCPPLib/console.h"
using namespace std;

/* Constants */

const int HASH_SEED = 5381;               /* Starting point for first cycle */
const int HASH_MULTIPLIER = 33;           /* Multiplier for each cycle      */
const int HASH_MASK = unsigned(-1) >> 1;  /* All 1 bits except the sign     */

/* Function prototypes */

int hashCode(string key);

/* Main program to test the hash function */

int main() {
   string name;
   cout << "Please enter your name: "; 
   getline(cin, name); 
   int code = hashCode(name);
   cout << "The hash code for your name is " << code << "." << endl;
   return 0;
}
int hashCode(string str) {
   unsigned hash = HASH_SEED;
   int nchars = str.length();
   for (int i = 0; i < nchars; i++) {
      hash = HASH_MULTIPLIER * hash + str[i];
   }
   return (hash & HASH_MASK);
}

它给我这个错误:

andre@ubuntu-Andre:~/Working/Assignment1-linux/0-Warmup$ g++ Warmup.cpp -o a
/tmp/ccawOOKW.o: In function `main':
Warmup.cpp:(.text+0xb): undefined reference to `_mainFlags'
Warmup.cpp:(.text+0x21): undefined reference to `startupMain(int, char**)'
collect2: ld returned 1 exit status

这里有什么问题吗?


更新: 现在可以使用了。

1. cd to the folder containing assignment.cpp
2. g++ assignment.cpp StanfordCPPLib/*.cpp -o a -lpthread

StanfordCPPLib/*.cpp this part indicate that everything in the library will be compiled,
-pthread will link pthread.h, which is used by several utilities in the Stanford library.

最佳答案

我在网上找到的随机 "StanfordCPPLib/console.h" 包含有趣的代码,例如:

#if CONSOLE_FLAG | GRAPHICS_FLAG

#define main main(int argc, char **argv) { \
extern int _mainFlags; \
_mainFlags = GRAPHICS_FLAG + CONSOLE_FLAG; \
return startupMain(argc, argv); \
} \
int Main

extern int startupMain(int argc, char **argv);

所以你的 main() 函数显然是一个名为 Main() 的函数,它最终由一些支持函数 startupMain() 调用>,这是在您的讲师应该提供的库中。

您需要链接到该库。您的作业或类(class)笔记应说明如何执行此操作以及图书馆的来源。

关于c++ - 编译斯坦福 C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16821546/

相关文章:

c++ - 模板类容器自动转换问题

objective-c - 存储到 'cell' 的值永远不会被读取

java - 为什么三元运算必须返回一个值?

.net - 不支持的重复项目不断出现

android - 使用 NDK 在 Android 上进行本地化/本地化

c++ - 分配没有一维的多维数组

c++ - 这个方法声明/定义是什么意思? (与传递数组有关?)

c++ - 将flex生成的代码放到一个普通的C++程序中

ios - Xcode项目中的禁止所有警告选项在构建时不会隐藏警告

c++ - 为什么不是所有的 cpp 文件都重新编译?