相关疑难解决方法(0)

使用GCC链接具有重复类名的库

GCC是否有办法在链接包含具有相同名称的类的库时生成警告?例如

Port.h

class Port {
public:
  std::string me();
};
Run Code Online (Sandbox Code Playgroud)

Port.cpp

#include "Port.h"
std::string Port::me() { return "Port"; }
Run Code Online (Sandbox Code Playgroud)

FakePort.h

class Port {
public:
  std::string me();
};
Run Code Online (Sandbox Code Playgroud)

FakePort.cpp

#include "FakePort.h"
std::string Port::me() { return "FakePort"; }
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "Port.h"

int main() {
  Port port;
  std::cout << "Hello world from " << port.me() << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

建造

# g++ -c -o Port.o Port.cpp
# ar rc Port.a Port.o
# g++ -c -o FakePort.o FakePort.cpp
# ar rc FakePort.a FakePort.o
# …
Run Code Online (Sandbox Code Playgroud)

c++ gcc

11
推荐指数
1
解决办法
2458
查看次数

为什么允许在几个cpp文件中重新定义类

让我有两个cpp文件:

//--a.cpp--//
class A
{
public:
    void bar()
    {
        printf("class A");
    }
};
//--b.cpp--//
class A
{
public:
    void bar()
    {
        printf("class A");
    }
};
Run Code Online (Sandbox Code Playgroud)

当我正在编译并将这些文件链接在一起时,我没有错误.但如果我写下以下内容:

//--a.cpp--//
int a;
//--b.cpp--//
int a;
Run Code Online (Sandbox Code Playgroud)

在编译和链接这些源代码后,我发现了一个错误,因为它的重新定义a.但是在我重新定义类的情况下,但没有引发错误.我糊涂了.

c++ class definition

8
推荐指数
1
解决办法
572
查看次数

C++/VS2005:在两个不同的.cpp文件中定义相同的类名

有些学术问题,但我在编写一些单元测试时遇到了这个问题.

我的单元测试框架(UnitTest ++)允许您创建结构以用作夹具.通常这些都是根据文件中的测试自定义的,所以我将它们放在单元测试文件的顶部.

//Tests1.cpp

struct MyFixture {  MyFixture() { ... do some setup things ...} };

TEST_FIXTURE(MyFixture, SomeTest)
{
  ...
} 

//Tests2.cpp

struct MyFixture { MyFixture() { ... do some other setup things, different from Tests1}};

 TEST_FIXTURE(MyFixture, SomeOtherTest)
 {
  ...
 }
Run Code Online (Sandbox Code Playgroud)

但是,我最近发现(至少使用VS2005),当你使用相同的名称命名fixture结构时(现在结构的两个版本存在同名),然后静默抛出其中一个版本.这是非常令人惊讶的,因为我将我的编译器设置为/ W4(最高警告级别)并且没有出现警告.我想这是一个名称冲突,为什么命名空间被发明,但我真的需要将每个单元测试装置包装在一个单独的命名空间中吗?我只是想确保我没有错过更基本的东西.

有没有更好的方法来解决这个问题 - 这应该发生吗?我不应该看到重复的符号错误或什么?

c++ namespaces visual-studio-2005 name-clash

3
推荐指数
1
解决办法
1346
查看次数