【问题标题】:Issue defining a variable at link time in Makefile在 Makefile 中的链接时定义变量的问题
【发布时间】:2023-03-25 17:24:01
【问题描述】:

好的,我应该在链接时定义一个变量 HASH_TABLE_SIZE,所以我会把它放在我的 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

为什么会这样?任何帮助将不胜感激。

【问题讨论】:

  • mkfile 的构建行上的 CFLAGS 在哪里?
  • 该错误是编译器错误,发生在链接步骤开始之前;编译器抱怨您在源代码中留下了占位符HASH_TABLE_SIZE。您确定要在链接时而不是编译时进行分配吗?

标签: c++ arrays linker makefile hashtable


【解决方案1】:

快速解决方案

你没有在你的食谱中使用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++ 程序,CXX 用于指定C++ 编译器。 Make 并不介意,但它可以在使用约定时更容易遵循。

LDFLAGS 通常用于传递链接时间标志,如-lrt,因此仅在第 6 行使用它才有意义,而不是在编译步骤中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多