仅包含头文件中的特定定义

时间:2018-06-16 04:54:34

标签: c header string.h

我使用了string.h库中的strlen()函数,但没有包含我想要包含在最初实现的头文件中的头文件,因为我正在编写自己的strcpy()实现,如果我包含了它说它是strcpy()的多个定义。 那么如何只包含头文件中的特定定义。 我需要使用extern关键字吗?

#include <stdio.h>
#include <stdlib.h>
#include "exercise 5.5.h"

int main() {
  char *s = "hello";
  char *t = "helli";
  int n = 3;
  if (n > strlen(t))
    printf("\nsorry the value of n is greater than the size of t");
  else {
    S = strncpy(s, t, n);
    printf("\nther is %d", x);
  }
}

标题包含strncpy

的定义

终端跟踪

exercise. 5.5_main.c:10:7: incompatible implicit declaration of built-in function "strien
exercise 5.5 main.c:10:7: note: include <string.h> or provide a declaration of 'strlen

我不想包含string.h但是如何明确提供strlen的定义

标题

char* strncat(char *s, char *t, int n);
char* strncpy(char *s, char *t, int n);
int strncmp(char *s,char *t, int n);

1 个答案:

答案 0 :(得分:3)

重新实现像strcpy这样的标准库函数可能会很棘手。由于它是标准的库函数,因此它的名称在某种意义上是&#34;保留&#34; - 你不应该自己使用它。 (它不像switch那样强烈保留,但尝试编写名为strcpy的函数仍然是一个坏主意 - 更不用说了事实上它通常是完全没必要的!)

在回答你明确的问题时,不,没有办法选择性地包括&#34;只是您自己选择系统头文件中的声明,例如<string.h>

如果出于某种原因需要编写自己的strcpy版本,根据具体情况,您有多种选择。

  1. 重命名您自己的功能。例如,将其命名为my_strcpy。 (这是通常的做法。)

  2. 确保函数的定义完全正确,并完全匹配标准头文件中的声明。例如,如果您有strcpy(char *dst, char *src) {...}char *strcpy(char *dst, char *src) {...},那么这些都是错误的 - 它必须是char *strcpy(char *dst, const char *src) {...}

  3. 也不要使用标准的strlen功能,这意味着您根本不必执行#include <string.h>。如果您需要,也可以编写自己的strlen版本。 (如果您编写自己的strcpy的原因是教学练习,通常需要这样做:通常,作业说明&#34;您可能不会使用标准库中的任何其他功能。&# 34)

  4. 您可以在文件顶部为#include <string.h>提供自己的原型,而不是strlen,因为您正在调用extern size_t strlen(const char *);。 (由于几个原因,这通常是一个非常糟糕的主意,除非在极端情况下以及当您确切知道自己在做什么时,这不是一个可以采取的步骤。)

  5. 注意&#34;重新定义&#34;是否也很重要。你得到的错误来自编译器或链接器。如果它是编译时错误,例如&#34; conflicting types for 'strcpy'&#34;,则表示您可能需要注意上面的第2点。但如果它是一个链接时错误,例如&#34; ld: duplicate symbol '_strcpy'&#34;你可能没有任何关于它的事情,你必须回到第1点。