Error c2061 syntax error identifier

When I compile there is an error call "error C2061: syntax error : identifier 'Player' " I can't figure out what is wrong with my code. Here is my code #include "Platform.h" #include "Player.h" c...

When I compile there is an error call «error C2061: syntax error : identifier ‘Player’ «

I can’t figure out what is wrong with my code. Here is my code

#include "Platform.h"
#include "Player.h"
class Collision
{
public:
  Collision(void);
  ~Collision(void);
  static bool IsCollision(Player &player, Platform& platform);
};

There is an error in «IsCollision» method.

Player.h

#include <SFML/Graphics.hpp>
#include "rapidxml.hpp"
#include <fstream>
#include <iostream>
#include "Collision.h"
using namespace rapidxml;
class Player
{
private:
    sf::Texture playerTexture;
    sf::Sprite playerSprite;
    sf::Vector2u position;
    sf::Vector2u source;
    sf::Vector2u size;
    int frameCounter, switchFrame, frameSpeed;
    int walkSpriteWidth;
    float velocity;
    bool isWalk;
    bool isStand;
    bool isFaceRight;

public:
    Player(void);
    ~Player(void);

    void Init();
    void Draw(sf::RenderWindow *window);
    void MoveForward();
    void MoveBackward();
    void Update(sf::Clock *clock);
    void SetSourceY(int value);
    void SetWalk(bool value);
    void SetFacing(std::string value);
    void SetStand(bool value);
    void Stand();
    std::string GetStatus();
    void PrintStatus();
    sf::Vector2f GetPosition();
    int GetWidth();
    int GetHeight();
};

georges619's user avatar

georges619

2881 gold badge7 silver badges18 bronze badges

asked Apr 3, 2013 at 8:32

aratn0n's user avatar

7

You have a circular include dependency. Collision.h includes Player.h and vice versa. The simplest solution is to remove #include "Collision.h" from Player.h, since the Collision class is not needed in the Player declaration. Besides that, it looks like some of your includes in Collision.h can be replaced by forward declarations:

// forward declarations
class Player;
class Platform;

class Collision
{
public:
  Collision(void);
  ~Collision(void);
  static bool IsCollision(Player &player, Platform& platform);
};

You can then put the includes in Collision‘s implementation file.

answered Apr 3, 2013 at 8:37

juanchopanza's user avatar

juanchopanzajuanchopanza

221k33 gold badges398 silver badges474 bronze badges

0

That’s a pretty common mistake — you have circular include dependency.

Looking at your code, you should replace #include "Player.h" with class Player; in Collision.h. This is called «forward declaration» and will break the circular dependency.


Also, it would be good to add include guards, for example:

#ifndef MY_PLAYER_CLASS
#define MY_PLAYER_CLASS

...

#endif

And this should be done for each header you write.

answered Apr 3, 2013 at 8:37

Kiril Kirov's user avatar

Kiril KirovKiril Kirov

37.1k22 gold badges111 silver badges185 bronze badges

Circular dependency or you’re using a C compiler for C++ code

answered Apr 8, 2019 at 16:09

Stocazzo's user avatar

1

Синтаксическая ошибка: идентификатор «Player». Файл mob.h ст 40
Гуглить пробовал. Ответ так и не нашел

player.h:

#pragma once
#include "Weapon.h"
#include "Mob.h"

class Player
{
public:
	int health, armor, exp, mana;
	int currentHealth, currentArmor, currentMana, toNextLvlExp, balance;
	int missChanceBody, missChanceHead, missChanceLegs;

	Weapon sword;
	Weapon magicStick;

	Player(int _health, int _armor, const Weapon& _sword, const Weapon& _magicStick);
	int takePhysicalDamage(Mob& m);
};

mob.h:

#pragma once
#include <string>
#include "Player.h"

using namespace std;

class Mob
{
public:
	enum mobType {
		PHYSIC,
		MAGIC
	};

	enum attackDir {
		HEAD,
		BODY,
		LEGS
	};

	int health, armor, magicResistance, shockResistance;
	int currentHealth, damage, spreadDamage;
	string name;
	mobType attackType;

	

	/**
	 * Конструктор класса Mob.
	 * Принимает 3 аргумента
	 * _health - здоровье моба
	 * _magicResistance - защита от магического урона
	 * _shockResistance - защита от физического урона
	 * _damage - урон
	 * _spreadDamage - Разброс урона
	 * _name - Имя моба
	 * type - тип атаки моба
	 */
	Mob(int _health, int _magicResistance, int _shockResistance, int _damage, int _spreadDamage, string _name, mobType type);
	int takePhysicalDamage(Player* player, attackDir dir);
	int takeMagicalDamage(Player* player, attackDir dir);
};

Содержание

  1. C2061: синтаксическая ошибка: идентификатор ‘строка’ — странное поведение
  2. Решение
  3. Другие решения
  4. ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’
  5. 1 ответы
  6. C ++: синтаксическая ошибка C2061: неожиданный идентификатор
  7. 5 ответы
  8. Синтаксическая ошибка: идентификатор (ошибка C2061)
  9. Решение
  10. Другие решения
  11. C2061 Синтаксическая ошибка (идентификатор)
  12. 2 ответы

C2061: синтаксическая ошибка: идентификатор ‘строка’ — странное поведение

Я пытаюсь изучать C ++, однако, параметр метода, который у меня есть в моем собственном классе, ведет себя неправильно. Когда он использует dataType типа int, он отлично работает без ошибок, но когда я пытаюсь изменить его на «string» dataType, программа вылетает с этой ошибкой.

Ошибка 1 ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’ в файле temp.h ln
8 цв 1

Я использую следующие классы:

РАБОЧИЙ КОД
TesterClass.cpp // Точка входа

Сломанный код
Temp.h

Когда я настраиваю параметр «blah» на строку, как в файле .h, так и в файле .cpp, возникает проблема.

Я огляделся, но ни один из ответов, похоже, не решил мою проблему. Я очень хотел бы помочь в этом, я вне идей. Я попытался переустановить C ++, возиться с:

Если вы знаете, как решить мою проблему, я хотел бы услышать от вас. Я более чем рад предоставить больше информации.

Решение

C ++ выполняет однопроходную компиляцию, поэтому std :: string необходимо объявить перед тем, как использовать его вообще — в том числе в заголовочном файле.

Я бы посоветовал вам быть более точным в ваших заголовочных файлах при указании таких классов, потому что вы можете легко встретить другую библиотеку, которая определяет свою собственную string и тогда вы столкнетесь с конфликтами имен. Спасти using импортировать операторы для ваших файлов cpp.

Другие решения

У πάντα ῥεῖ был письменный ответ, спасибо!

Они сказали использовать std :: string при необходимости, а также #include в заголовочном файле.

Источник

ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’

это, вероятно, проблема с включением, я получаю эти ошибки по всему коду, а не только для строкового идентификатора, например error C2146: syntax error : missing ‘;’ before identifier ‘getName’ и error C2146: syntax error : missing ‘;’ before identifier ‘name’

вот пример класса:

вот мой stdafx.h файл:

задан 14 мая ’12, 19:05

using пространство имен в заголовочном файле — ужасная идея. Любой файл, который включает ваш заголовок, теперь имеет using namespace std; в нем (это плохо). — Ed S.

спасибо, удалил. еще не исправлено — Michael

Прямо не показано, что это проблема в опубликованном вами коде, поскольку то, что вы опубликовали, не показывает, что они используются, но макросы, заканчивающиеся точкой с запятой, почти всегда будут вызывать проблемы. — Michael Burr

@MichaelBurr: Хорошо, если ты уберешь это, тогда string сразу становится неопределенным (используйте std::string вместо). Кроме того, почему ваши #define s заканчиваются точкой с запятой? — Ed S.

@Майкл, потому что stdafx.h для вашего предварительно скомпилированного заголовочного файла. Он включен везде, поэтому вы хотите помещать в него только те вещи, которые необходимы везде и не меняются часто. Если положить все в stdafx.h каждый раз, когда вы изменяете один из своих заголовков, вы должны перекомпилировать весь проект, а не только измененную часть. Общее эмпирическое правило заключается в том, чтобы включать как можно меньше заголовков в заголовки. — AJG85

1 ответы

Итак, я скомпилировал ваш код в том виде, в котором он был опубликован, без ваших пользовательских файлов заголовков, и он работал нормально. Исходя из этого, я собираюсь поспорить, что у вас есть проблема в одном из этих заголовочных файлов:

Это может быть макрос, класс/структура, не оканчивающаяся точкой с запятой, и т. д. Проверьте это.

Напоследок несколько второстепенных вопросов:

Во-первых, using пространство имен в заголовочном файле — ужасная идея. Любой файл, который включает ваш заголовок, теперь имеет using namespace std; в нем (это плохо). Вы, вероятно, не хотите включать так много файлов заголовков в каждый файл, который включает stdafx.h .

Во-вторых, как только вы удалите это, то string сразу становится неопределенным (вместо этого используйте std::string).

Наконец, почему ваш #define s заканчиваются точкой с запятой? В этом нет необходимости.

Источник

C ++: синтаксическая ошибка C2061: неожиданный идентификатор

Что не так с этой строкой кода?

bar foo (вектор ftw);

задан 11 июн ’10, 19:06

5 ответы

попробуйте вместо этого std :: vector. Кроме того, убедитесь, что вы

Возможно, вы забыли включить вектор и / или импорт std::vector в пространство имен.

Убедитесь, что у вас есть:

или просто используйте:

блин, обыграй меня на секунду 😉 — Адриан Григоре

using namespace std; в вашем коде?

определяет std::vector class, поэтому вам нужно включить его где-нибудь в вашем файле.

так как вы используете vector , вам нужно указать компилятору, что вы собираетесь импортировать весь std пространство имен (возможно, это не то, что вы хотите делать) через using namespace std;

В противном случае вектор должен быть определен как std::vector

стараться std::vector or using std;

Сам по себе этот фрагмент кода не имеет определения bar , vector or odp . Что касается того, почему вы не получаете сообщение об определении bar , Я могу только предположить, что вы вырвали это из контекста.

Я предполагаю, что он должен определять foo как функция, что vector называет шаблон и что он должен определять параметр, называемый ftw но в объявлении все, что фактически не определяется, должно быть объявлено заранее, чтобы компилятор знал, что означают все остальные идентификаторы.

Например, если вы определяете новые типы следующим образом, вы получаете фрагмент, который будет скомпилирован:

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c++ syntax compiler-errors or задайте свой вопрос.

Источник

Синтаксическая ошибка: идентификатор (ошибка C2061)

Я ненавижу публиковать что-то настолько тонкое, но это совершенно не дает мне понять, что я делаю неправильно:
Когда я компилирую, это совсем не нравится Class Simulator. Я получаю ошибку

в каждом экземпляре симулятора я использую внутри заголовочного файла DOCO. Это также делает это для моей структуры Pellet. Код работал совершенно нормально, пока я не начал добавлять функции, которые работают с классом Simulator, в DOCO.h.
Класс Simulator использует структуру DOCO, а структура DOCO использует класс Simulator. Это проблема? Может быть, я использовал мои заголовки неправильно?

Вот ссылка на ошибку, которую я получаю, если она помогает: http://msdn.microsoft.com/en-us/library/yha416c7.aspx

Заголовочные файлы:
Simulator.h

Решение

Как я уже говорил выше, ваша проблема связана с рекурсивным включением.

Вы можете сделать одну из двух вещей:

1) Измените свой класс симулятора так, чтобы вы использовали ссылки на DOCO или указатели на DOCO, и таким образом forward declare DOCO.

2) Измените свой заголовок DOCO, чтобы использовать указатели на Simulator или ссылки на Simulator, а затем просто вперед объявить Simulator ,

Самый простой способ изменить (если эти комментарии в вашем коде остаются) — это изменить DOCO.h :

Внутри DOCO определение структуры, вы можете указать ссылки и указатели на Simulator , а не симулятор объектов.

Я также советую не положил using namespace std; в заголовочном файле. Это обсуждается во многих темах на SO, почему вы не должны иметь эту строку в заголовочном файле.

Другие решения

Я уверен, что вы не хотели заранее объявить классы.

Источник

C2061 Синтаксическая ошибка (идентификатор)

Это всего лишь один файл .c в проекте. Вот код:

задан 02 сен ’10, 04:09

Эта ошибка может быть вызвана взаимозависимыми файлами заголовков. — Grault

2 ответы

bool не относится к типу C.

Я подозреваю BOOL где-то определяется.

То же самое касается использования true и false .

Не могу поверить, что я это пропустил, я занимался C ++ прямо перед тем, как начал это, спасибо. — гитара

C99 действительно имеет bool во всей красе. Хорошая ссылка на Windows и ее булевы (и похожие) здесь: blogs.msdn.com/b/oldnewthing/archive/2004/12/22/329884.aspx — ласково

На самом деле, bool является допустимым типом (ну, фактически, макросом) в стандарте C99, если вы используете последний компилятор. Вам необходимо добавить:

Обратите внимание, что bool не действует в более старых вариантах стандартов C. ANSI, C89, C90 и т. д.

Как подчеркнул JeremyP в комментариях, компилятор Microsoft C по-прежнему не имеет надлежащей поддержки функций C99.

Остается три альтернативы:

  1. Считайте это C ++, а не C; потому что C ++ имеет bool как встраиваемый
  2. Создайте свой собственный bool реализация
  3. Перепишите код, чтобы избежать использования bool

Для варианта 2 что-то вроде этого будет работать, но это уродливый обходной путь:

Он не использует последний компилятор, он использует Microsoft Visual C, который не поддерживает C99. — ДжеремиП

Хорошая точка зрения. Я предполагал, что Microsoft добавила бы его в какой-то момент в последнее десятилетие, но они, кажется (после некоторого чтения) игнорируют C99, вместо этого сосредотачивая свои усилия на C ++ 0x. — Саймон

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c compiler-errors syntax-error or задайте свой вопрос.

Источник

  • Remove From My Forums
  • Question

  • Hi,

    I am a newbie in Mircosoft Visual C++. Currerntly, I am working on a project to combine certain function in Matlab with Visual C++. However, it gives me syntax error,identifier ‘mxArray’. Is there anybody having any idea regarding this kind of error?

    const char *model_to_matlab_structure(mxArray *plhs[], int num_of_feature, struct svm_model *model);
    struct svm_model *matlab_matrix_to_model(const mxArray *matlab_struct, const char **error_message);

    These are the two function that include the use of mxArray. Actually, they are functions from libsvm library created by a Taiwanese,cjlin. It is available in http://www.csie.ntu.edu.tw/~cjlin/libsvm .

    Hope to hear from anybody soon.

    Thanks.

Answers

  • Well…I have never worked with Matlab thus again can only provide information I have remembered from some forum/article. LNK2001 simply means that the linker cannot find the definition of a function. This is usually due to a missing reference to a library. Matlab requires some libraries your application need to link against such as libmx.lib, libmex.lib and libmat.lib. Whether you require all or only some I can’t say though.

  • /FORCE:MULTIPLE is almost never a good idea. Typically, you would get something like this for non-inline functions declared in a header:

    E.g.:

    // myheader.h

    void foo() {}

    // a.cpp

    #include «myheader.h»

    // b.cpp

    #include «myheader.h»

    // error duplicate definition

    To resolve this define the function as inline.

    However, as you say these mexFunctions are in fact different. This violates the ODR (=One Definition Rule) and that’s what the linker complains about. In C++ you can have several copies of functions with the same signature in distinct translation units of a single program, so long as they

    • do not have external C linkage and are either

    • static namespace-scope functions

    • or directly or indirectly enclosed in an anonymous namespace

    From the error message it sounds like you’re using C code or C++ with C linkage. Making your functions static should allow the image to link (Static in this context restricts the symbol binding of the function to the particular object file) 

    -hg

Hi All ,
I have an interface IDemo.
The methods in this interface are implemented in the class globalWCFService.cs (C#)

I want to use a method in the interface in another dll( Managed C++ project)
by referring the namespace of globalWCFService class as follows.

But it is giving below errors. Please let me know how to resolve this.

IDemo^ target = (IDemo^)gcnew GlobalWcfService();

target->Method();

Errors:
MyClass.cpp(3106): : error C2061: syntax error :
identifier ‘GlobalWcfService’
Thanks,
Sudhakar


You must pay attention to the exact writing: The «G» is great in your code, above little «g» written.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

0 / 0 / 0

Регистрация: 14.01.2011

Сообщений: 5

12.03.2011, 22:17

6

Возникает Error C2061: синтаксическая ошибка: идентификатор «Odr_int»
(в 95 строке)
подскажите как исправить

Код

#include <yazpp/z-assoc.h>

namespace yazpp_1 {

class Z_Server;

class YAZ_EXPORT Z_ServerUtility {
 public:
    void create_databaseRecord (ODR odr, Z_NamePlusRecord *rec,
                                const char *dbname, const Odr_oid *format,
                                const void *buf, int len);
    void create_surrogateDiagnostics(ODR odr, Z_NamePlusRecord *rec,
                                     const char *dbname, int error,
                                     char *const addinfo);

    Z_Records *create_nonSurrogateDiagnostics (ODR odr, int error,
                                               const char *addinfo);

    void create_diagnostics (
        ODR odr, int error, const char *addinfo,
        Z_DiagRec ***dreca, int *num);

    virtual ~Z_ServerUtility() = 0;
};

class YAZ_EXPORT IServer_Facility {
 public:
    virtual int init(Z_Server *server,
                     Z_InitRequest *initRequest,
                     Z_InitResponse *initResponse) = 0;
    virtual int recv(Z_Server *server, Z_APDU *apdu) = 0;

    virtual ~IServer_Facility() = 0;
};

class YAZ_EXPORT Yaz_Facility_ILL : public IServer_Facility {
 public:
    virtual void ill_service (Z_ExtendedServicesRequest *req,
                              Z_ItemOrder *io,
                              Z_ExtendedServicesResponse *res) = 0;

    int init(Z_Server *server,
             Z_InitRequest *initRequest,
             Z_InitResponse *initResponse);
    int recv(Z_Server *server, Z_APDU *apdu);
};

class YAZ_EXPORT Yaz_Facility_Update : public IServer_Facility {
 public:
    virtual void update_service (Z_ExtendedServicesRequest *req,
                                 Z_IUUpdate *io,
                                 Z_ExtendedServicesResponse *res) = 0;

    virtual void update_service0 (Z_ExtendedServicesRequest *req,
                                 Z_IU0Update *io,
                                 Z_ExtendedServicesResponse *res) = 0;

    int init(Z_Server *server,
             Z_InitRequest *initRequest,
             Z_InitResponse *initResponse);
    int recv(Z_Server *server, Z_APDU *apdu);
};


class YAZ_EXPORT Yaz_Facility_Retrieval : public IServer_Facility,
    public Z_ServerUtility {
 public:

    virtual int sr_init (Z_InitRequest *initRequest,
                         Z_InitResponse *initResponse) = 0;
    virtual void sr_search (Z_SearchRequest *searchRequest,
                            Z_SearchResponse *searchResponse) = 0;
    virtual void sr_present (Z_PresentRequest *presentRequest,
                             Z_PresentResponse *presentResponse) = 0;
    virtual void sr_record (const char *resultSetName,
                            int position,
                            Odr_oid *format,
                            Z_RecordComposition *comp,
                            Z_NamePlusRecord *namePlusRecord,
                            Z_Records *diagnostics) = 0;
    int init(Z_Server *server,
             Z_InitRequest *initRequest,
             Z_InitResponse *initResponse);
    int recv(Z_Server *server, Z_APDU *apdu);

    ODR odr_encode();
    ODR odr_decode();
 private:
    Z_Records *pack_records (Z_Server *s,
                             const char *resultSetName,
                             int start, int num,
                             Z_RecordComposition *comp,
                             Odr_int *next, Odr_int *pres,
                             Odr_oid *oid);

    void fetch_via_piggyback (Z_Server *s,
                              Z_SearchRequest *searchRequest,
                              Z_SearchResponse *searchResponse);
    void fetch_via_present (Z_Server *s,
                            Z_PresentRequest *req, Z_PresentResponse *res);

    int m_preferredMessageSize;
    int m_maximumRecordSize;
    ODR m_odr_encode;
    ODR m_odr_decode;
};

class YAZ_EXPORT Z_Server_Facility_Info {
    friend class Z_Server;
    IServer_Facility *m_facility;
    char *m_name;
    Z_Server_Facility_Info *m_next;
};



class YAZ_EXPORT Z_Server : public Z_Assoc {
public:
    Z_Server(IPDU_Observable *the_PDU_Observable);
    virtual ~Z_Server();
    void recv_Z_PDU(Z_APDU *apdu, int len);
    virtual void recv_GDU(Z_GDU *apdu, int len);
    void facility_add(IServer_Facility *facility, const char *name);
    void facility_reset ();


 private:
    Z_Server_Facility_Info *m_facilities;
};

class YAZ_EXPORT Yaz_USMARC {
 public:
    const char *get_record(size_t position);
};
};
/*
 * Local variables:
 * c-basic-offset: 4
 * c-file-style: "Stroustrup"
 * indent-tabs-mode: nil
 * End:
 * vim: shiftwidth=4 tabstop=8 expandtab
 */



0



trying to write to my output file in a function but it shows this error
Snips of code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void PrintScoresAndHands(int ComputerHand[], const int ComputerCardCount, int PlayerHand[], const int PlayerCardCount, char Player[15], int &WhatNow, fstream wins, int Player1win&, int Player1lose&, int &Player1tie, int &Computerwin, int &Computerlose, int &Computertie); // Print ending score for single player
void mPrintScoresAndHands(int Player2Hand[], const int Player2CardCount, int PlayerHand[], const int PlayerCardCount, char Player[15], int &WhatNow, char Player2[15]); // Print ending score for two player


int main() {
	using namespace std;
	//Random number generator, number is different each second. Super random numbers.
	// Seeds number generator with the time
	time_t qTime;				     
	time(&qTime);				// time function
	srand(qTime);				// pass time to srand

	//Declare
	fstream wins;				// Output file
	bool CardDeck[52];			// Deck of cards, 52 cards
	int ComputerCardCount = 0;	// Set card count to 0, computer
	int PlayerCardCount = 0;	// Set card count to 0, player
	int Player1CardCount = 0;	// Set card count to 0, Player 1 in two player
	int Player2CardCount = 0;	// Set card count to 0, player 2 in two player
	int ComputerHand[12];		// Computer cards, possable 12 random numbers
	int PlayerHand[12];			// Players 1 cards, possable 12 random numbers, anymore cards would bust
	int Player2Hand[12];		// Player 2 cards, possable 12 random numbers, anymore cards would bust
	char Player[15];			// Player 1's name
	char Player2[15];			// Player 2's name
	int WhatNow;				// Menu after hand weather to play again or exit
	int Choice;					// Main menu choice of single player, two player, or exit

	//Files
	wins.open("wins.dat");		//Open file, output file 

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@leocavalcante

@evanmiller

ssize_t is signed size_t, should be okay.

Please post full compiler version and output if there is an error.

@leocavalcante

~ cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

@QuLogic

Compiling C or C++? Is this fixed/broken by #49?

@evanmiller

I think the problem was removing <sys/types.h>. I have restored it in dev.

@leocavalcante

Not yet :/

libxls [master]~ git rev-parse HEAD
e5fe0ab9555a02b04e067487898da623e2bcff6e

libxls [master]~ .build.ps1
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

xls.c
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2061: syntax error: identifier 'ole2_read'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: ';'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: '<parameter-list>'
.srcxls.c(1628): warning C4047: 'return': 'const char *' differs in levels of indirection from 'int'
xlstool.c
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2061: syntax error: identifier 'ole2_read'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: ';'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: '<parameter-list>'
ole.c
c:usersleoprojectslibxlssrc../include/libxls/ole.h(181): error C2061: syntax error: identifier 'ole2_read'
c:usersleoprojectslibxlssrc../include/libxls/ole.h(181): error C2059: syntax error: ';'
c:usersleoprojectslibxlssrc../include/libxls/ole.h(181): error C2059: syntax error: '<parameter-list>'
.srcole.c(58): error C2061: syntax error: identifier 'sector_read'
.srcole.c(58): error C2059: syntax error: ';'
.srcole.c(58): error C2059: syntax error: '<parameter-list>'
.srcole.c(59): error C2061: syntax error: identifier 'read_MSAT'
.srcole.c(59): error C2059: syntax error: ';'
.srcole.c(59): error C2059: syntax error: '<parameter-list>'
.srcole.c(161): error C2061: syntax error: identifier 'ole2_read'
.srcole.c(161): error C2059: syntax error: ';'
.srcole.c(161): error C2059: syntax error: '<parameter-list>'
.srcole.c(388): error C2061: syntax error: identifier 'ole2_read_header'
.srcole.c(388): error C2059: syntax error: ';'
.srcole.c(388): error C2059: syntax error: '<parameter-list>'
.srcole.c(457): error C2061: syntax error: identifier 'ole2_read_body'
.srcole.c(457): error C2059: syntax error: ';'
.srcole.c(457): error C2059: syntax error: '<parameter-list>'
.srcole.c(636): error C2061: syntax error: identifier 'sector_read'
.srcole.c(636): error C2059: syntax error: ';'
.srcole.c(636): error C2059: syntax error: '<parameter-list>'
.srcole.c(657): error C2061: syntax error: identifier 'read_MSAT_header'
.srcole.c(657): error C2059: syntax error: ';'
.srcole.c(657): error C2059: syntax error: '<parameter-list>'
.srcole.c(677): error C2061: syntax error: identifier 'read_MSAT_body'
.srcole.c(677): error C2059: syntax error: ';'
.srcole.c(677): error C2059: syntax error: '<parameter-list>'
.srcole.c(738): error C2061: syntax error: identifier 'read_MSAT_trailer'
.srcole.c(738): error C2059: syntax error: ';'
.srcole.c(738): error C2059: syntax error: '<parameter-list>'
.srcole.c(783): error C2061: syntax error: identifier 'read_MSAT'
.srcole.c(783): error C2059: syntax error: ';'
.srcole.c(783): error C2059: syntax error: '<parameter-list>'
endian.c
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2061: syntax error: identifier 'ole2_read'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: ';'
c:usersleoprojectslibxlsincludelibxls../libxls/ole.h(181): error C2059: syntax error: '<parameter-list>'
Generating Code...

If I find for all occurrences of ssize_t and replace by size_t then build:

libxls [master]~ .build.ps1
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

xls.c
xlstool.c
ole.c
endian.c
Generating Code...
Microsoft (R) Incremental Linker Version 14.16.27027.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:xls.dll
/dll
/implib:xls.lib
xls.obj
xlstool.obj
ole.obj
endian.obj

libxls [master]~ ls | grep .dll
-a----         3/8/2019  11:33 AM         253952 xls.dll

Voilà!

build.ps1
Remove-Item .*.obj

cl `
  -I . `
  -I .include `
  -LD `
  .srcxls.c `
  .srcxlstool.c `
  .srcole.c `
  .srcendian.c

bootstrap and configure to have a config.h by MSYS2.
And indeed it works fine on MSYS2 gcc.

@leocavalcante

«ssize_t msvc» on Google is very elucidating. It seems that it is POSIX compliant only, not standard C.

Found some cool answers that it could be defined:

#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#include <limits.h>
#include <stddef.h>

#if SIZE_MAX == UINT_MAX
typedef int ssize_t;        /* common 32 bit case */
#elif SIZE_MAX == ULONG_MAX
typedef long ssize_t;       /* linux 64 bits */
#elif SIZE_MAX == ULLONG_MAX
typedef long long ssize_t;  /* windows 64 bits */
#elif SIZE_MAX == USHRT_MAX
typedef short ssize_t;      /* is this even possible? */
#else
#error platform has exotic SIZE_MAX
#endif

@silvioprog

hi dudes. since the build passes fine in the appveyor CI, it would be nice to send the libxls to the msys2 repositories allowing something like this via mingw console: pacman -S libxls. :-)


Recommended Answers

Not sure if in Visual_Basic works like this, but in Borland C++ Builder worked just fine

void __fastcall TForm1::Button3Click(TObject *Sender)
{
int k;
k=5   ;
Label1->Caption = k;
}

Jump to Post

Mixing C++/CLI and standard C++ can be troublesome. Try sticking to one or the other unless you have good reason not to:

label2->Text = Convert::ToString ( a );

Jump to Post

All 6 Replies

Member Avatar

13 Years Ago

Not sure if in Visual_Basic works like this, but in Borland C++ Builder worked just fine

void __fastcall TForm1::Button3Click(TObject *Sender)
{
int k;
k=5   ;
Label1->Caption = k;
}

Member Avatar

13 Years Ago

Looks like ye’ need to perform a good ol’ int-to-string conversion. Today we’ll be creating an ‘ostringstream’ object derived from the <sstream> library in order to facilitate our int-to-string needs:

#include<sstream>
#include<string>
#include<iostream>

using namespace std;

int main()
{
     ostringstream int_to_str;
     string temp;
     int a = 0;

     cout << "Enter a number fool: ";
     cin >> a;

     int_to_str << a;
     temp = int_to_str.str();

     cout << "String " << temp << " == int " << a;

     return 0;
}

Edited

13 Years Ago
by Clinton Portis because:

you can’t fight the funk.

Member Avatar

13 Years Ago

vidmaa, this doesn’t work with Visual.


Clinton, it does not work in my situation. I am sure it is going to work if I do it as console application. However it does not work with the Forms :(

Edited

13 Years Ago
by hajiakhundov because:

n/a

Member Avatar

13 Years Ago

I looked around a bit, what I found out is that we actually need to convert an int to System::String. Who can help me with that?

Member Avatar


Narue

5,707



Bad Cop



Team Colleague


13 Years Ago

Mixing C++/CLI and standard C++ can be troublesome. Try sticking to one or the other unless you have good reason not to:

label2->Text = Convert::ToString ( a );

Member Avatar

13 Years Ago

Narue, thanks a lot! It worked finally :)


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • Error c2059 syntax error declspec dllexport
  • Error c2057 требуется константное выражение
  • Error c2039 string is not a member of std
  • Error c2036 void unknown size
  • Error c2027 использование неопределенного типа