当文件相互依赖时,如何使用g ++将多个cpp文件编译为单个可执行文件? [英] How do I compile multiple cpp files into a single executable using g++ when the files are interdependent?

查看:76
本文介绍了当文件相互依赖时,如何使用g ++将多个cpp文件编译为单个可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用c ++制作一个可以接受极高值的计算器.我为数字创建了一个类,该类已在标题中定义.我的第一个cpp文件包含基本功能,例如加,减,乘和除(链接).我的第二个cpp文件包含类定义,这些类定义使我可以根据需要操作数字对象(链接).我的第三个cpp文件是主文件,它还没有很多(链接).我正在尝试使用以下命令将这些文件链接在一起:

I'm making a calculator in c++ that accepts extremely high values. I made a class for the numbers, which I've defined in a header. My first cpp file contains basic functions like add, subtract, multiply, and divide (link). My second cpp file contains class definitions, which allow me to manipulate the number objects as needed (link). My third cpp file is the main, which doesn't have much yet (link). I'm trying to link these files together using:

g++ -o bignumbers bignum_funcdefs.cpp bignum_classdefs.cpp main.cpp

据我所读,以这种方式通过g ++传递多个文件与一次传递一个文件没有什么不同.显然问题是bignum_classdefs.cpp需要bignum_funcdefs.cpp中的函数,但是我不知道如何使它们可访问.我也尝试过这个:

From what I've read, passing multiple files through g++ in this fashion is no different than passing them one at a time. Obviously the problem is that bignum_classdefs.cpp needs the functions from bignum_funcdefs.cpp, but I don't know how to make them accessible. I also tried this:

g++ -c bignum_funcdefs.cpp
g++ -c bignum_classdefs.cpp bignum_funcdefs.o

但是这给了我与funcdefs中的函数尚未定义相同的错误.我会以错误的方式处理吗?有没有办法使这些文件按其原样工作?有没有更好的方法来构造我的cpp文件,类和标头?整个回购可以在此处找到,非常感谢任何建议.使用我的代码提出的具体建议会有所帮助.

But this gives me the same errors that the functions in funcdefs haven't been defined. Am I going about this the wrong way? Is there a way to make these files work the way they are? Is there a better way to structure my cpp files, classes, and headers? The entire repo can be found here, any advice is much appreciated. Specific suggestions using my code would help even more.

推荐答案

分隔类定义和实现.将类的设计放在 .h 文件中,并将其包含在两个cpp文件中.这是将项目扩展到单个文件之外的典型模式.

Separate your class definition and your implementation. Put the design of the class in a .h file and include it in both cpp files. This is the typical pattern for scaling projects beyond a single file.

还声明(但不实现)在一个文件中的任何函数,而在 .h 文件中的另一个函数调用.通常看起来像这样:

Also declare (but not implement) any functions that are in one file and called by the other in the .h file. This typically looks like:

extern bignum addNumbers(bigNumber &, bigNumber &) ;

我看到您的类有一个 .h ,所以只需将 bignum_funcdefs.cpp 中的所有函数声明添加到 bignum_decs.h的底部

I see you have a .h for your class, so just add all declarations for the functions from bignum_funcdefs.cpp into the bottom of bignum_decs.h

这篇关于当文件相互依赖时,如何使用g ++将多个cpp文件编译为单个可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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