【问题标题】:How to compile multiple .c and .h files in gcc linux?如何在 gcc linux 中编译多个 .c 和 .h 文件?
【发布时间】:2013-02-17 04:04:54
【问题描述】:

所以我有一个源 mainClass.c,我在其中定义了 main。我有一个头文件class1.h和class1.c中定义的所有函数的实现。我在 class1.h 中有两个变量(全局),分别命名为 cond 和 mutex,它们现在正在 class1.c 中使用,将来我可能也会在我的 mainClass.c 中使用它。 现在要编译所有源文件以生成一个目标文件,我正在执行以下操作:

gcc -Wall -pthread -I/home/2008/ariarad/mainClass1 mainClass1.c class1.c -o out

/home/2008/ariarad/mainClass1 是我所有的头文件和源文件所在的位置,我在其中一个 .c 文件中使用 pthead.h。即使我已将其包含在其中,它也会抱怨,因此我必须将其包含在内。

现在,当我运行上述命令时,我收到以下错误:

class1.c:3:16: error: redefinition of ‘cond’
class1.h:66:16: note: previous definition of ‘cond’ was here
class1.c:4:17: error: redefinition of ‘mutex’
class1.h:67:17: note: previous definition of ‘mutex’ was here

以防万一我在 class1.h 周围有一个 ifndef 和 endif 块,以避免多重包含。我绝对不会重新定义 .c 文件的头文件中定义的变量。那么有人可以帮助我为什么它仍然给我错误?

【问题讨论】:

  • 只是为了确定?你有#ifndef CLASS1_H_ / #define CLASS1_H_ / #endif 与你的代码之间?你需要的不仅仅是#ifndef

标签: c gcc


【解决方案1】:

您不能在头文件中定义全局变量。您必须在其中一个 .c 文件中定义它们,然后在头文件中使用 extern

在 .c 文件之一中:

int cond;

在其中一个 .h 文件中,所有需要该变量的 .c 文件都必须包含该文件:

extern int cond;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 2011-03-13
    相关资源
    最近更新 更多