编译斯坦福C ++库

时间:2013-05-29 18:43:15

标签: c++ compilation compiler-errors ld

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

我正在自学这门课程,即将开设的Coursera课程。我在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.

1 个答案:

答案 0 :(得分:3)

我在网上找到的随机"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()调用,该函数位于教师应提供的库中。

您需要链接到该库。您的作业或课程笔记应该有关于如何操作以及库来自何处的说明。