在其他.cpp文件中使用struct [英] Using struct in different .cpp file

查看:36
本文介绍了在其他.cpp文件中使用struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中有两个.cpp文件,main.cpp和myfile.cpp

I have two .cpp files in one project, main.cpp and myfile.cpp

我在main.cpp中全局定义了结构mystruct,现在我想在myfile.cpp中使用此结构.当我在头文件中写入mystruct并将其包含在两个cpp文件中时,出现错误,提示mystruct重定义.我该如何解决这个问题.

I have globaly defined struct mystruct in main.cpp, now I want to use this struct in myfile.cpp. When I write mystruct in a header file and include in both cpp files I get an error, saying mystruct redefinition. How should I solve this problem.

推荐答案

如果要在多个编译单元(cpp文件)之间共享结构的定义,则常见的方法是:将结构的定义放在头文件(mystruct.h)中.如果结构包含任何方法(默认情况下它是一个所有成员都是公共的类),则可以在mystruct.CPP文件中实现它们;或者,如果它们是轻量级的,则可以直接在结构中实现(这使得它们默认内联.

If you are trying to share the definition of a struct among several compilation units (cpp files), the common way is this: Place the definition of your struct in a header file (mystruct.h). If the struct contains any methods (i.e. it is rather a class with all member public by default), you can implement them in mystruct.CPP file, or, if they're lightweight, directly within the struct (which makes them inline by default).

mystruct.h:

mystruct.h:

#ifndef MYSTRUCT_H
#define MYSTRUCT_H

struct MyStruct
{
    int x;
    void f1() { /* Implementation here. */ }
    void f2(); /* Implemented in mystruct.cpp */
};

#endif

mystruct.cpp

mystruct.cpp

#include "mystruct.h"
// Implementation of f2() goes here
void MyStruct::f2() { ... }

您可以根据需要在多个cpp文件中使用您的结构,只需 #include mystruct.h:

You can use your struct in as many cpp files as you like, simply #include mystruct.h:

main.cpp

#include "mystruct.h"
int main()
{
    MyStruct myStruct;
    myStruct.x = 1;
    myStruct.f2();
    // etc...
}

另一方面,如果您试图在多个编译单元之间共享该结构的全局实例(您的问题尚不清楚),请执行上述操作,但还要添加

If, on the other hand, you are trying to share a global instance of the struct across several compilation units (it's not absolutely clear from your question), do as above but also add

extern MyStruct globalStruct;

到mystruct.h.这将宣布具有外部链接的实例可用;换句话说,变量存在但已在其他地方初始化(在您的情况下,在mystruct.cpp中).将全局实例的初始化添加到mystruct.cpp中:

to mystruct.h. This will announce that an instance is available with external linkage; in other words that a variable exists but is initialized elsewhere (in your case in mystruct.cpp). Add the initialization of the global instance to mystruct.cpp:

MyStruct globalStruct;

MyStruct globalStruct;

这很重要.无需手动创建 globalStruct 的实例,您将获得链接器错误.现在,您可以从每个包含mystruct.h的编译单元访问 globalStruct .

This is important. Without manually creating an instance of globalStruct, you'd get unresolved-external linker errors. Now you have access to globalStruct from each compilation unit that includes mystruct.h.

这篇关于在其他.cpp文件中使用struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆