如何将MySQL凭据移动到include.h?

以下代码可以正常工作。但是..
我想将MySQL凭据移动到test.h

script.c

#include  #include  #include  #include  #include  #include "test.h" int main() { while (FCGI_Accept() >= 0) { char query[300]; MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = ""; char *database = "a"; conn = mysql_init(NULL); if (mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { sprintf(query, "select * from table limit 1"); mysql_query(conn, query); res = mysql_use_result(conn); row = mysql_fetch_row(res); } printf("Content-type: text/html;\r\n"); printf("\r\n"); printf("%s", row[1]); FCGI_Finish(); } return 0; } 

好的,让我们将所有这些复制并移动到test.h
test.h

 char query[300]; MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = ""; char *database = "a"; conn = mysql_init(NULL); 

尝试编译script.c

 In file included from test.c:7: test.h:11: warning: data definition has no type or storage class test.h:11: error: conflicting types for 'conn' test.h:3: note: previous declaration of 'conn' was here test.h:11: warning: initialization makes integer from pointer without a cast test.h:11: error: initializer element is not constant 

实际上有更多的错误。 我只粘贴了前几行。

在头文件中使用#define

 // test.h #define SERVER "localhost" #define PASSWORD "" 

将其余部分保留在源代码文件中。

 // script.c char *server = SERVER; char *user = USER; 

如果要在其他C源文件中使用script.c中的函数,最佳选择是:

  • script.c定义这些函数。
  • test.h 声明这些函数(BTW – 通用命名约定将是script.h )。
  • 然后,您可以从任何其他.c文件(与script.c一起编译)中包含script.c并使用这些声明的函数。

关于变量 – 您可以在.h文件中#define它们,或者将它们保留在.c文件中并使用getter函数包装它们,然后在上面为函数编写的内容中声明这些函数。 例如:

script.c你将拥有:

 char *server = "localhost"; ... const char *get_server(void) { return server; } 

.h文件中,您将声明:

 const char *get_server(void); 

有时需要将函数定义放在.h文件中,但通常你必须有充分的理由(比如内联函数 )。 在您的情况下,您不需要它,将其保存在.c源文件中。