简体   繁体   English

为什么我的程序仅适用于调试版本?

[英]Why does my program only work with the debug build?

I have a project that has the main method accessing another method from another source file, BigDog(int) . 我有一个项目,该项目的main方法是从另一个源文件BigDog(int)访问另一个方法。 I'm pretty sure the code is right but CodeBlocks seems to not be able to detect the definition of the method unless I build the other file using debug build in CodeBlocks. 我很确定代码是正确的,但是CodeBlocks似乎无法检测方法的定义,除非我在CodeBlocks中使用debug build来构建另一个文件。 In Release, I get the following error when building: 在发行版中,构建时出现以下错误:

Error: undefined reference to 'BigDog(int)' 错误:未定义对“ BigDog(int)”的引用

Why is that so? 为什么会这样?

main.cpp main.cpp

#include <iostream>

using namespace std;

void BigDog(int KibblesCount);

int main()
{
   BigDog(3);
   return 0;
}

mystuff.cpp mystuff.cpp

 #include <iostream>

 using namespace std;

 void BigDog(int KibblesCount)
 {
     cout << KibblesCount;
 }

If you're adding a new file in codeblocks, make sure to check the checkmarks in the dialog to add it to both the debug and the release build. 如果要在代码块中添加新文件,请确保选中对话框中的复选标记以将其添加到调试和发行版本中。

Also its better practice to move your declarations to a header file and include that where needed, like this: 还有一个更好的做法是将声明移动到头文件并在需要的地方包括它,如下所示:

main.cpp: main.cpp:

#include "mystuff.h"

int main()
{
    BigDog(3);
    return 0;
}

mystuff.h: mystuff.h:

#pragma once

void BigDog(int KibblesCount);

mystuff.cpp: mystuff.cpp:

#include "mystuff.h"

#include <iostream>

void BigDog(int KibblesCount)
{
    // add a newline so the line gets printed immediately
    std::cout << KibblesCount << "\n"; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM