c++ - 使用另一个 C 文件中的 switch case 调用方法?

标签 c++ c

我正在尝试从 Choice.c 文件调用方法“choice_1”和“choice_2”,使用 switch case 语句我想在 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 时,我得到了

[Linker error] undefined reference to 'choice_1'

[Linker error] undefined reference to 'choice_2'

菜单.c

int main(void){
int count[2];
...
while(TRUE) {
      printf("%s\n", "Menu:");
      printf("%s\n", "1) Option 1");
      printf("%s\n", "2) Option 2");
      ...
      printf("%s\n", "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'

这是因为您的函数定义在另一个文件中。你需要同时编译两者。这样你就可以摆脱链接器错误

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

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

关于c++ - 使用另一个 C 文件中的 switch case 调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19185357/

相关文章:

c - 程序中的 "error: stray ‘\344’是什么意思?

c++ - 如何将度数转换为弧度?

c++ - 为什么使用右值引用时unique_ptr的所有权没有转移?

C malloc 指向 NULL 的指针不起作用

c - C 应用程序中未处理的 win32 异常

c - 使用dup,pipe,fifo与子进程通信

android - 启用 OpenMP 支持的 Clang/LLVM

c++ - 将元素插入容器 : copy constructor messes up pointers

c++ - 关于包含不可复制成员引用的类的复制构造函数的建议

c - C 程序中的意外输出