错误:为"constructor"特性指定的参数数目错误

Error: wrong number of arguments specified for ‘constructor’ attribute

本文关键字:错误 quot 参数 数数 constructor      更新时间:2023-10-16

在实际实现之前,我写了一个小的原型代码,并将类构造函数和ctor构造函数放在同一个文件中,看看ctor是否会首先执行,这就是我的实际实现。

然而,我面临着一个错误。这是代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
extern "C" void startMe(void) __attribute__ ((constructor(1)));
extern "C" void ending(void) __attribute__ ((destructor));
class Test {
 public:
    Test()
    {
      cout << "This is test constructor" << endl;
    }
 };
 int main()
 {
  Test();
  printf("Now main calledn");
 }
 void startMe(void)
 {
  printf("Start me called before mainn");
 }
 void ending(void)
 {
  printf("Destructor calledn");
 }

--

Output:
 $ g++ constructor1.cc 
 constructor1.cc:10: error: wrong number of arguments specified for ‘constructor’ attribute

但是,当我删除构造函数优先级时,它会编译并运行良好。也就是说,我做:

extern "C" void startMe(void) __attribute__ ((constructor)); 

为什么会这样?如何给予优先权?

请帮帮我。我的想法是应该先执行"ctor",然后执行另一个(Test(构造函数。出于同样的原因,我将ctor作为优先级1。

按原样编译程序会产生:

warning: constructor priorities from 0 to 100 are reserved for the implementation

将优先级从1更改为101将消除警告,可执行文件将生成:

 Start me called before main
 This is test constructor
 Now main called
 Destructor called

这是使用GCC 4.5

为"构造函数"属性指定的参数数目错误

看起来您使用的是GCC的下层版本。

根据GCC 4.2.1文件,以下是相关的GCC 4.2.1功能属性:

构造函数
析构函数
 nbsp nbsp;构造函数属性导致函数在执行进入main ()。。。

以及相关GCC 4.3.0功能属性:

构造函数
析构函数
构造函数(优先级(
析构函数(优先级(
 nbsp nbsp;构造函数属性导致函数在执行进入main ()。。。

解决方案是使用GCC 4.3或更高版本。

我目前正在OpenBSD 5.7上测试一些软件,它附带了GCC 4.2.1编译器。我们还支持CentOS 5,它与GCC 4.1编译器一起提供。下面是out代码的样子:

// INIT_PRIORITY manages initialization of C++ static objects. Under GCC, 
// the library uses init_priority attribute in the range [INIT_PRIORITY,
// INIT_PRIORITY+100]. Under Windows, INIT_PRIORITY enlists
// "#pragma init_seg(lib)". Undefine or set to 0 to disable it.
#define INIT_PRIORITY 250
#ifdef __GNUC__
# define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
#ifdef __clang__
# define CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#endif
...
#if __GNUC__ && INIT_PRIORITY && ((GCC_VERSION >= 40300) || (CLANG_VERSION >= 20900))
DLL void API DetectX86Features() __attribute__ ((constructor (INIT_PRIORITY + 50)));
DLL bool API CpuId(word32 input, word32 *output);
#elif __GNUC__ && INIT_PRIORITY
DLL void API DetectX86Features() __attribute__ ((constructor));
DLL bool API CpuId(word32 input, word32 *output);
#else
DLL void API DetectX86Features();
DLL bool API CpuId(word32 input, word32 *output);
#endif

您可能应该创建一个额外的类,如Initialization,并将startMe放在构造函数中,将ending放在析构函数中。然后,创建一个C++对象的静态实例,如Initialization init;

为了避免静态初始化顺序失败,您应该使用init_priority(另请参阅GCC邮件列表上的堆栈溢出问题和属性init_priority的澄清(。init_priority至少从GCC 3.2开始就存在了。