我在代码中有以下条件:
标题文件:
functionality.h:
#ifndef functionality_h
#define functionality_h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*The field value attribute declaration*/
#define size_adhaar 3000
#define size_aspid 8
#define size_input 65
#define size_esignClass 2
#define size_sc 2
#define size_ver 4
#define size_txn 45
/*Replacement string declaration */
extern const char replace_adhaar[];
extern const char replace_aspid[];
extern const char replace_input[];
extern const char replace_esignClass[];
extern const char replace_sc[];
extern const char replace_ver[];
extern const char replace_txn[];
/*Max length of field attribute*/
extern int max_adhaar_size;
extern int max_aspid_size;
extern int max_input_size;
extern int max_esignClass_size;
extern int max_sc_size;
extern int max_ver_size;
extern int max_txn_size;
/*
The declaration of the field attribute.
*/
char adhaar[size_adhaar];
char aspid[size_aspid];
char input[size_input];
char esignClass[size_esignClass];
char sc[size_sc];
char ver [size_ver];
char txn[size_txn];
void incorrect_val_test(FILE *, FILE *, FILE *, FILE *, FILE *, FILE *, FILE *, FILE *, FILE *);
#endif
和functional.c
#include "functionality.h"
#include "function.h"
/* Initialization Block starts*/
const char replace_adhaar[] = "REPLACE_Adhaarii_";
const char replace_aspid[] = "REPLACE_aspidii_";
const char replace_input[] = "REPLACE_Inputii_";
const char replace_esignClass[] = "REPLACE_esignClassii_";
const char replace_sc[] = "REPLACE_scii_";
const char replace_ver[] = "REPLACE_verii_";
const char replace_txn[] = "REPLACE_txnii_";
/*Max length of field attribute*/
int max_adhaar_size = 3000;
int max_aspid_size = size_aspid+sizeof(replace_aspid);
int max_input_size = size_input+sizeof(replace_input);
int max_esignClass_size = size_esignClass+sizeof(replace_esignClass);
int max_sc_size = size_sc+sizeof(replace_sc);
int max_ver_size = size_ver+sizeof(replace_ver);
int max_txn_size = size_txn+sizeof(replace_txn);
/*Field true value initialization*/
char adhaar[size_adhaar] = {"RbEY0VVRJNVFtNDhMMGh0WVdNK1BDOUJkWFJvPQ=="};
char aspid[] = {"ASP-101"};
char input[] = {"936a185caaa266bb9cbe981e9e05c"};
char esignClass[] = {"1"};
char sc[] = {"Y"};
char ver[] = {"1.0"};
char txn[] = {"2250dc54-79e8-42ad-b86b-7ec09759"};
/*Initialization Block end*/
void incorrect_val_test(FILE *fp_adhaar, FILE *fp_aspid, FILE *fp_input, FILE *fp_esignClass, FILE *fp_sc, FILE *fp_ver, FILE *fp_ts, FILE *fp_txn, FILE *fp_vtxn)
{
//Some processing done here.
}
问题是如果我在头文件中初始化变量然后因为头文件包含在多个源文件中,所以编译器会给出多个定义错误。
如果我只在头文件中声明它并在其中一个源文件中初始化,那么相同的变量会在代码中重复写入两次。
这使代码看起来冗长而笨拙。
那么有更好的出路:
1。要么我在同一个地方宣布和初始化 2.如何通过函数初始化它并在main()中调用它 或其他东西,以便代码看起来更少。
因为我们必须在头文件中声明大量变量并在源文件中使用完全相同的签名初始化它们。对于我们的导师来说,他看起来像是在重复同样的事情。应该有更好的方法。谢谢......
答案 0 :(得分:0)
你正在声明一大堆变量 - 它绝对不是干净的代码(鲍勃叔叔的清洁代码可以帮助你)
如果你真的想这样做 - 你需要在头文件中用“extern”声明所有全局变量,并在源文件中定义它们。它会导致你的所有文件,包括带有全局变量的标题“知道”你的变量,它会使你的所有变量只在内存中创建一次(因为每个源文件只编译一次)。
请记住 - 在99%的情况下,您可以编写没有任何全局变量的程序。