如何从多个c ++文件构建二进制文件?

时间:2013-05-31 23:35:02

标签: c++

我已经开始学习C ++了,在处理多个文件时遇到了困难。为了练习基础课,我写了三个不同的文件,

  • working.cpp
  • word.cpp
  • word.h

word.cpp:

#include <iostream>
#include "word.h"
using namespace std;
class word{

public:
char *word;

void createWord(char *str)
{
    word = str;
}

void print_word(void)
{
    cout<<word<<endl;
}

char * getWord()
{
    return word;
}

}

working.cpp

#include <iostream>
#include "word.h"
void printWord(word);
using namespace std;
int main()
{
word one;
one.createWord("one");

printWord(one);

}

void printWord(word a)
{
cout<<a.getWord()<<endl;
}

word.h

class word;

这是三个不同的文件,所以我不知道如何编译它们。我试过的是 g++ working.cpp word.cpp

但是,编译器不会将word识别为类,并且给出了以下错误

working.cpp: In function 'int main()':
working.cpp:7:7: error: aggregate 'word one' has incomplete type and cannot be defined
working.cpp:7:12: error: aggregate 'word two' has incomplete type and cannot be defined
working.cpp:7:17: error: aggregate 'word three' has incomplete type and cannot be defined
working.cpp: In function 'void printWord(word)':
working.cpp:19:6: error: 'aha' has incomplete type
In file included from working.cpp:2:0:
word.h:2:7: error: forward declaration of 'class word'
word.cpp:25:1: error: expected ';' after class definition

编译时我做错了什么?

3 个答案:

答案 0 :(得分:4)

  1. 您需要在头文件中包含更多word的定义。像这样:

    class word
    {
    public:
        char *word;
        void createWord(char *str);
        void print_word(void);
        char * getWord();
    };
    
  2. 然后,将word.cpp更改为只有实现:

    void word::createWord(char *str)
    {
        word = str;
    }
    
    void word::print_word(void)
    {
        cout<<word<<endl;
    }
    
    char * word::getWord()
    {
        return word;
    }
    
  3. 编译并链接!

  4. 您需要在标题中包含更多word类,以便您的其他翻译单元可以知道该类的大小(为您正在创建的实例保留足够的空间)以及知道要调用的方法的名称。

答案 1 :(得分:3)

仅提及头文件中的类名(所谓的前向声明)是不够的;你需要一个完整的类声明(声明该类的所有字段和函数):

class word {
public:
    char *word;
    void createWord(char *str);
    void print_word(void);
    char * getWord();
};

答案 2 :(得分:3)

word

中没有实际的word.h类声明
word.h:2:7: error: forward declaration of 'class word'

我建议你阅读Bjarne Stroustrup的精彩书籍“The C ++ Programming Language”来开始。