【问题标题】:Write a library without class and cpp file [closed]编写一个没有类和cpp文件的库[关闭]
【发布时间】:2017-06-18 08:55:36
【问题描述】:

我想在标题中编写以下函数。这样做的语法是什么?

int added (uint8_t a, uint8_t b){
int r;
r=a+b;
return r;
}

【问题讨论】:

  • 您的问题到底是什么?它似乎对我有用,但你需要#include <cstdint>。请尝试以下操作:#include <cstdint> inline int added(uint8_t a, uint8_t b) { return a + b; }
  • 只需将其设为inline 函数,您就可以将其放在标题中。
  • @Thomas Flinkow 我手头有一个更复杂的问题。我需要弄清楚执行此操作的语法,但是在谷歌上搜索了几个小时却没有找到示例。上面的代码只是一个测试。
  • @Atmega328 那么你应该向我们展示你的复杂问题
  • @Thomas Flinkow 你说得对,但我的情况有点尴尬。假设我的复杂问题正在上床,但我无法与女孩交谈。所以也许从简单的事情开始?让我在打出本垒打之前先登陆一垒。

标签: c++


【解决方案1】:

确保您的 .h 有保护。

#pragma once

要么在标题中声明函数内联:

inline int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

将其声明为静态也可以。

static int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

或者,如果你的函数很大,或者你有一个循环依赖,把它的声明只放在头文件中。

extern int added (uint8_t a, uint8_t b); // extern keyword is optional

和 cpp 文件中的正文

int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

就这么简单。

一些编译器不支持#pragma once,并且为了避免在编译 cpp 时头文件中的声明出现两次(这可能会产生编译器警告和错误),他们使用宏来代替。

#ifndef FILENAME_H  // check if this header file was already read, using a unique macro name
#define FILENAME_H  // no. define the unique macro now, so we'll not read this section again

//  this section will only be read once.

#endif              // end the section protected by FILENAME_H

【讨论】:

  • 不敢相信这么简单。那些indef和define让我头疼。
  • 我想知道我是否不应该将其添加到答案中。现在你已经得到它了。我会的,
猜你喜欢
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
相关资源
最近更新 更多