繁体   English   中英

如何在标头中声明const?

[英]How do I declare a const in a header?

我想测试在标头中定义一个const并在函数中使用它,然后调用它。 但是我得到了错误,我添加了包括防护措施,但无济于事。 错误为:LNK1169:找到一个或多个定义的乘法符号。 我怎样才能做到这一点? 唯一的解决方案是在.h中声明const并在.cpp中定义此const,然后在所有其他.cpps中包括此.cpp吗?

标头

#ifndef STORY
#define STORY
const int x = 4;
#endif

.cpp

#include <iostream>
#include "8-04.h"

void func1()
{
    int w = x;
    std::cout << "func1 " << w << std::endl;
}

.cpp

#include <iostream>
#include "8-04.h"

void func2()
{
    int z = x;
    std::cout << "func2 " << z << std::endl;
}

主要

#include <iostream>
#include "8-04.h"
#include "8-04first.cpp"
#include "8-04second.cpp"

using namespace std;

int main()
{
    func1();
    func2();
}

问题是每个.cpp都包含.h。 这意味着每个.o都包含const int x 当链接器将它们链接在一起时,您将获得多个定义。

解决方法是修改.h

#ifndef STORY
#define STORY
extern const int x;  //Do not initialise
#endif

并在一个 .cpp中:

const int x=4

编辑:我什至没有看到#include <file.cpp>业务。 不要那样做 这太糟糕了。

这应该像:

header.h:

#ifndef STORY
#define STORY
const int x = 4;
void func1();
void func2();
#endif

fun1.cpp

#include <iostream>
#include "header.h"

void func1()
{
    int w = x;
    std::cout << "func1 " << w << std::endl;
}

fun2.cpp

#include <iostream>
#include "header.h"

void func2()
{
    int z = x;
    std::cout << "func2 " << z << std::endl;
}

main.cpp

#include <iostream>
#include "header.h"

using namespace std;

int main()
{
    func1();
    func2();
}

您不能包含“ .cpp”

可以这样完成:

header.h:

#ifndef STORY
#define STORY
const int x = 4;
void func1();
void func2();
#endif

fun1.cpp

#include <iostream>
#include "header.h"
using namespace std;

void func1()
{
    int w = x;
    cout << "func1 value of w = " << w << "\n";
}

fun2.cpp

#include <iostream>
#include "header.h"
using namespace std;

void func2()
{
    int z = x;
    cout << "func2 value of z = " << z << "\n";
}

main.cpp

#include <iostream>
#include "header.h"

int main()
{
    func1();
    func2();
}

“ .cpp”文件不能包含在主源文件中。

暂无
暂无

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

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