2014-03-26 31 views
0

好吧,我应该在链接时定义一个变量HASH_TABLE_SIZE,所以我会把它放在我的makefile中。在Makefile中定义一个链接时变量的问题

我的Makefile文件如下:

1 CC = g++ 
    2 CFLAGS = -c -g -std=c++11 -Wall -W -Werror -pedantic -D HASH_TABLE_SIZE=10 
    3 LDFLAGS = -lrt 
    4 
    5 myhash : main.o hash.o hash_function.o 
    6  $(CC) $(LDFLAGS) main.o hash.o hash_function.o -o myhash 
    7 
    8 main.o : main.cpp hash.h 
    9  $(CC) $(LDFLAGS) main.cpp 
    10 
    11 hash.o : hash.cpp hash.h 
    12  $(CC) $(LDFLAGS) hash.cpp 
    13 
    14 hash_function.o : hash_function.cpp hash.h 
    15  $(CC) $(LDFLAGS) hash_function.cpp 
    16 
    17 clean : 
    18  rm *.o myhash 

我的Makefile似乎是正确的给我,我把-D HASH_TABLE_SIZE = 10。 然而,当我做,我得到这个错误:

In file included from main.cpp:3:0: 
hash.h:24:27: error: 'HASH_TABLE_SIZE' was not declared in this scope 
list<string> hashTable[HASH_TABLE_SIZE]; 

我Hash.h文件如下:

1 /* This assignment originated at UC Riverside. The hash table size 
2 should be defined at link time. Use -D HASH_TABLE_SIZE=X */ 
3 
4 #ifndef __HASH_H 
5 #define __HASH_H 
6 
7 #include <string> 
8 #include <list> 
9 
10 using namespace std; 
11 
12 class Hash { 
13 
14 public: 
15 Hash(); 
16 void remove(string word); 
17 void print(); 
18 void processFile(string fileName); 
19 bool search(string word); 
20 void output(string fileName); 
21 void printStats(); 
22 
23 private: 
24 list<string> hashTable[HASH_TABLE_SIZE]; 
25 int collisions; 
26 int longestList; 
27 double avgLength; 
28 
29 private: 
30 int hf(string ins); 
31 double newAvgListLen; 
32 
33 // put additional variables/functions below 
34 // do not change anything above! 
35 
36 }; 
37 
38 #endif 

这究竟是为什么?任何帮助将不胜感激。

+1

哪里是你的CFLAGS在你的mkfile的构建线? – JayInNyc

+0

错误是编译器错误,在链接步骤开始之前发生;编译器抱怨你已经在源代码中留下了占位符'HASH_TABLE_SIZE'。您确定要在链接时完成作业,而不是编译时间? – Beta

回答

2

快速解决方案

所以它有没有影响你没有使用你的食谱CFLAGS

如果你改变线路8至15到它应该工作:

8 main.o : main.cpp hash.h 
9  $(CC) $(CFLAGS) main.cpp 
10 
11 hash.o : hash.cpp hash.h 
12  $(CC) $(CFLAGS) hash.cpp 
13 
14 hash_function.o : hash_function.cpp hash.h 
15  $(CC) $(CFLAGS) hash_function.cpp 

一些额外的细节

-D是编译时间标志不是一个链接时选项。

CFLAGS通常用于将编译时标志传递给C程序的编译器。 通常CXXFLAGS将用于C++程序(如this)和CXX来指定C++编译器。尽管Make并不介意,但它可以使使用约定时更容易遵循。

LDFLAGS通常用于传递链接时间标志,如-lrt,所以它只适用于第6行,而不是编译步骤。