【发布时间】:2018-03-20 11:06:21
【问题描述】:
我有三个文件。 test.ctest.h 和 use.c。他们每个人的代码如下所示:
test.h:
#pragma once
#define unused __attribute__((unused))
typedef int cmd_fun_t(struct tokens *tokens);
typedef struct fun_desc {
cmd_fun_t *fun;
char *cmd;
char *doc;
} fun_desc_t;
int cmd_exit(struct tokens *tokens);
int cmd_help(struct tokens *tokens);
int cmd_pwd(struct tokens *tokens);
int cmd_cd(struct tokens *tokens);
test.c:
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/signal.h>
#include "test.h"
#include "tokenizer.h"
fun_desc_t cmd_table[] = {
{cmd_help, "?", "show this help menu"},
{cmd_exit, "exit", "exit the command shell"},
{cmd_pwd, "pwd", "print working directory"},
{cmd_cd, "cd", "change directory"},
};
int cmd_pwd(unused struct tokens *tokens){
char cwd[8192];
if (getcwd(cwd, sizeof(cwd)) != NULL)
fprintf(stdout, "%s\n", cwd);
else
perror("Error Occured");
return 1;
}
int cmd_cd(unused struct tokens *tokens){
if(chdir(tokens_get_token(tokens, 1)) == -1){
fprintf(stdout, "No such file or directory.\n");
return -1;
}
return 1;
}
/* Prints a helpful description for the given command */
int cmd_help(unused struct tokens *tokens) {
for (unsigned int i = 0; i < sizeof(cmd_table) / sizeof(fun_desc_t); i++)
printf("%s - %s\n", cmd_table[i].cmd, cmd_table[i].doc);
return 1;
}
/* Exits this shell */
int cmd_exit(unused struct tokens *tokens) {
exit(0);
}
使用.c:
#include "test.h"
int main(){
for(int i = 0; i < sizeof(cmd_table); i++){
}
return 0;
}
我的假设是这应该很好,但是当我编译代码时,它给出了以下错误:
‘cmd_table’未声明(在此函数中首次使用)for(int i = 0; i
有什么建议为什么会发生这种情况?
【问题讨论】:
-
您认为
sizeof(cmd_table)究竟应该是什么?我不明白这一点。cmd_table仍然在 .c 文件中声明,该文件不在use.c的范围内。 -
是的,但它是全球性的。不应该 use.c 查看 test.c 的全局变量
-
你能编译 test.c 吗?
-
是什么让你认为
use.c可以“看到”cmd_table? -
...无论如何从
test.c外部访问cmd_table是糟糕的设计。
标签: c file compiler-errors compilation header