C ++使用.h和.cpp文件

时间:2018-02-07 19:47:34

标签: c++

我对C ++完全不熟悉,并希望通过从有组织的文件中提取它们来使用我在程序中的函数。我不明白为什么我的代码(见下文)不起作用,我试图找到答案,但实际上不能。无论如何,这是代码,希望它有所帮助。

我的.h文件:

#ifndef MYMATH_H_INCLUDED
#define MYMATH_H_INCLUDED
#endif // MYMATH_H_INCLUDED

int sum (int,int);

My.cpp文件:

#include <iostream>
#include "myMath.h"

int sum(int a, int b){
return a+b;
}

我的主要人物:

#include <iostream>
#include "myMath.h"

using namespace std;

int main()
{
   int a, b;
   cin >> a;
   cin >> b;
   cout << sum(a,b);
}

最后是错误块:

||=== Build: Debug in using my functions (compiler: GNU GCC Compiler) ===|
obj\Debug\main.o||In function `main':|
C:\Users\Barcanjo\Desktop\Coding\using my functions\main.cpp|11|undefined 
reference to `sum(int, int)'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

2 个答案:

答案 0 :(得分:4)

您似乎没有将my.cpp对象与main.cpp链接。

以下内容应解决问题:

$ g++ main.cpp my.cpp -o my
$ ./my

答案 1 :(得分:1)

你的标题是错误的。你需要:

#ifndef MYMATH_H_INCLUDED
#define MYMATH_H_INCLUDED

int sum (int,int);

#endif // MYMATH_H_INCLUDED

在您当前的代码中,包含守卫实际上并不保护任何东西。

甚至更好,只需使用它:

#pragma once

int sum (int,int);

(随机的人会跳进来说这不是标准的C ++,但你可以放心地忽略它们。#pragma once是保护头文件不受多重包含的事实上的标准方法。)

现在出现构建错误。在我看来,你根本没有构建myMath.cpp文件。确保已将该文件添加到IDE中的项目中,因为它是实际实现sum()函数的文件。

如果您没有使用IDE并且手动构建,那么请立即构建所有源文件:

g++ main.cpp myMath.cpp

或者将文件编译成目标文件并在最后链接它们:

g++ -c main.cpp
g++ -c myMath.cpp
g++ main.o myMath.o

您可以使用-o标志指定生成的可执行文件的名称。默认情况下,它是a.out