使用另一个 C 文件中的开关大小写调用方法

Call a method using switch case from another C file?

本文关键字:开关 大小写 调用 方法 另一个 文件      更新时间:2023-10-16

我正在尝试使用 switch case 语句从 Choice.c 文件中调用方法 "choice_1" 和 "choice_2" 我想在 Menu.c 文件中输入并返回结果后调用选项,菜单处于循环中并且可以工作,我知道这一点,因为我将方法从 Choice.c 文件移动到 Menu.c 文件中, 一些调整,一切正常,但当它们在单独的文件中时就不行了......

我在两个文件的标题中都有"#includes Menu.h"。

我在头文件中还有 2 个函数:

void choice_1(int * count, char * text);
void choice_2(int * count, char * string);

当我尝试编译 Menu.c 时,我得到

[链接器错误] 未定义对"choice_1"的引用

[链接器错误] 未定义对"choice_2"的引用

菜单.c

int main(void){
int count[2];
...
while(TRUE) {
      printf("%sn", "Menu:");
      printf("%sn", "1) Option 1");
      printf("%sn", "2) Option 2");
      ...
      printf("%sn", "5) Exit");         
      fgets (userinput)...
...
      switch(userinput){
          case 1:
              choice_1(count);
              break;
          case 2:
              choice_2(count);
              break;
          ...
          case 5:
              return(EXIT_SUCCESS);
              break;
...

选择.c

....
void choice_1(int * count, char * text){
....
}
void choice_2(int * count, char * string){
....
}

它只是不调用 2 种方法,我做错了什么? :S

当我尝试编译 Menu.c 时,我得到

    [Linker error] undefined reference to 'choice_1'
    [Linker error] undefined reference to 'choice_2'

这是因为您的函数定义位于另一个文件中。 您需要在可以摆脱链接器错误的 time.so 进行编译

如果你像这样编译,你可以摆脱这个链接器错误

gcc menu.c choice.c -o out
./out

您的函数choice_1并且choice_2需要两个参数,而您只将一个参数传递给choice_1choice_2

switch(userinput){
      case 1:
          choice_1(count);  
          break;  //   ^ only one argument
      case 2:
          choice_2(count);
          break;  //   ^ only one argument  

也改变

return(EXIT_SUCCESS);  

return EXIT_SUCCESS;

一旦你得到所有文件中匹配的函数的签名,你也需要将choice.c文件"链接"到menu.c,因为它包含choice_1choice_2的定义。否则,编译器找不到这两个函数的定义,因此会引发错误 - [Linker error] undefined reference to 'your_function_name'