Trading Forex com opções binárias Opções binárias são uma maneira alternativa de jogar o mercado de moeda estrangeira (forex) para os comerciantes. Embora eles sejam uma maneira relativamente cara para o comércio de forex, em comparação com o mercado de forex forçado alavancado oferecido por um número crescente de corretores. O fato de que a perda potencial máxima é limitado e conhecido com antecedência é uma grande vantagem das opções binárias. Mas primeiro, quais são as opções binárias. São opções com resultado binário, ou seja, liquidam a um valor pré-determinado (geralmente 100) ou 0. Esse valor de liquidação depende se o preço do ativo subjacente à opção binária está sendo negociado acima ou abaixo do preço de exercício por vencimento . As opções binárias podem ser usadas para especular sobre os resultados de várias situações, como será o SampP 500 subir acima de um certo nível até amanhã ou na próxima semana, será esta semana reivindicações desempregados ser maior do que o mercado espera, ou será o euro ou ienes declínio Contra o dólar de ESTADOS UNIDOS hoje O ouro do dito está negociando em 1.195 por a onça troy atualmente e você está confiante que estará negociando acima de 1.200 mais tarde esse dia. Suponha que você pode comprar uma opção binária no ouro negociando em ou acima de 1.200 por aqueles dias perto, e esta opção está negociando em 57 (oferta) / 60 (oferta). Você compra a opção em 60. Se o ouro fecha em ou acima de 1.200, como você esperou, seu pagamento será 100, o que significa que seu ganho bruto (antes das comissões) é de 40 ou 66,7. Por outro lado, se o ouro fechar abaixo de 1.200, você perderia seu investimento 60, para uma perda de 100. Compradores e Vendedores de Opções Binárias Para o comprador de uma opção binária, o custo da opção é o preço pelo qual a opção está sendo negociada. Para o vendedor de uma opção binária, o custo é a diferença entre 100 eo preço da opção e 100. Do ponto de vista dos compradores, o preço de uma opção binária pode ser considerado como a probabilidade de que o comércio será bem sucedido. Portanto, quanto maior o preço da opção binária, maior a probabilidade percebida de o preço do ativo subir acima da greve. Do ponto de vista dos vendedores, a probabilidade é 100 menos o preço da opção. Todos os contratos de opção binária estão totalmente garantidos, o que significa que ambos os lados de um contrato específico, o comprador eo vendedor têm de colocar o capital para o seu lado do comércio. Então, se um contrato está negociando em 35, o comprador paga 35, eo vendedor paga 65 (100 - 35). Este é o risco máximo do comprador e vendedor, e é igual a 100 em todos os casos. Assim, o perfil de risco-recompensa para o comprador e vendedor neste caso pode ser afirmado da seguinte forma: Comprador Risco máximo 35 Recompensa máxima 65 (100 - 35) Vendedor Risco máximo 65 Prêmio máximo 35 (100 - 65) Opções binárias em opções binárias Forex Em forex estão disponíveis a partir de trocas como Nadex. Que os oferece nos pares mais populares como USD-CAD, EUR-USD e USD-JPY, bem como em um número de outros pares de moedas amplamente negociados. Estas opções são oferecidas com expirations que variam de intraday a diário e semanal. O tamanho do tique no forex binários spot de Nadex é 1, eo valor do tick é 1. As opções binárias intradiários forex oferecidas por Nadex expiram por hora, enquanto as diárias expiram em determinados horários definidos ao longo do dia. As opções binárias semanais expiram às 15:00 na sexta-feira. No mundo frenético de forex, como é o valor de validade calculado Para contratos de forex, Nadex leva os preços de ponto médio dos últimos 25 comércios no mercado de forex. Elimina os cinco mais altos e os mais baixos cinco preços e, em seguida, leva a média aritmética dos restantes 15 preços. A partir de 15 de dezembro de 2014, para contratos de forex, a Nadex propôs tomar os últimos 10 preços médios no mercado subjacente, remover os três mais altos e os três preços mais baixos e tomar a média aritmética dos quatro preços restantes. Vamos usar o par de moedas EUR-USD para demonstrar como opções binárias podem ser usadas para negociar forex. Usamos uma opção semanal que expirará às 3 da manhã da sexta-feira ou daqui a quatro dias. Suponha que a taxa de câmbio actual é EUR 1 USD 1.2440. Considere os dois cenários a seguir: (a) Você acha que o euro provavelmente não se enfraquecerá até sexta-feira e deve ficar acima de 1,2425. A opção binária EUR / USDgt1.2425 é cotada em 49.00 / 55.00. Você compra 10 contratos para um total de 550 (excluindo comissões). Às 15h00 da sexta-feira, o euro está sendo negociado a US $ 1,2450. Sua opção binária se instala em 100, dando-lhe um pagamento de 1.000. Seu ganho bruto (antes de levar as comissões em conta) é de 450, ou aproximadamente 82. No entanto, se o euro tivesse fechado abaixo de 1,2425, você perderia todo o investimento de 550, por uma perda de 100. (B) Você é bearish no euro e acredita que poderia declinar por sexta-feira, diga a USD 1.2375. A opção binária EUR / USDgt1.2375 é cotada em 60.00 / 66.00. Desde que você é bearish no euro, você venderia esta opção. Seu custo inicial para vender cada contrato de opção binária é, portanto, 40 (100 - 60). Suponha que você vender 10 contratos, e receber um total de 400. Às 3 horas da sexta-feira, vamos dizer que o euro está negociando em 1,2400. Uma vez que o euro fechou acima do preço de exercício de 1,2375 por vencimento, você perderia o total de 400 ou 100 de seu investimento. E se o euro tivesse fechado abaixo de 1,2375, como você esperava nesse caso, o contrato se liquidaria em 100, e você receberia um total de 1.000 para seus 10 contratos, para um ganho de 600 ou 150. Estratégias Básicas Adicionais Você faz Não tem que esperar até a expiração do contrato para perceber um ganho em seu contrato de opção binária. Por exemplo, se na quinta-feira, o euro está negociando no mercado à vista em 1,2455, mas você está preocupado com a possibilidade de uma queda na moeda se os dados econômicos dos EUA a serem divulgados na sexta-feira são muito positivos. Seu contrato de opção binária (EUR / USDgt1.2425), que foi cotado em 49.00 / 55.00 no momento de sua compra está agora em 75/80. Você, portanto, vender os 10 contratos de opção que você tinha comprado em 55 cada, para 75, e reservar um lucro total de 200 ou 36. Você também pode colocar em um comércio de combinação de menor risco / menor recompensa. Vamos considerar a opção binária USD / JPY para ilustrar. Suponha que sua opinião é que a volatilidade no iene que está negociando em 118.50 ao dólar poderia aumentar significativamente, e poderia negociar acima de 119.75 ou declinar abaixo de 117.25 em sexta-feira. Você compra 10 contratos de opção binária USD / JPYgt119.75, negociando em 29.50 / 35.50 e também vende 10 contratos de opção binária USD / JPYgt117.25, negociando em 66.50 / 72.00. Portanto, você paga 35,50 para comprar o contrato USD / JPYgt119.75 e 33,50 (ou seja, 100 - 66,50) para vender o contrato USD / JPYgt117,25. Seu custo total é, portanto, 690 (355 335). Três cenários possíveis surgem por expiração da opção às 3 da tarde na sexta-feira: O iene está negociando acima de 119.75. Neste caso, o contrato USD / JPYgt119.75 tem um pagamento de 100, enquanto o contrato USD / JPYgt117.25 expira sem valor. Seu pagamento total é de 1.000, para um ganho de 310 ou cerca de 45. O iene está sendo negociado abaixo de 117,25. Neste caso, o contrato USD / JPYgt117.25 tem um pagamento de 100, enquanto o contrato USD / JPYgt119.75 expira sem valor. Seu pagamento total é 1.000, para um ganho de 310 ou cerca de 45. O iene está negociando entre 117,25 e 119,75. Neste caso, ambos os contratos expiram sem valor e você perde o investimento total 690. Opções binárias têm um par de inconvenientes: a recompensa ascendente ou total é limitada, mesmo se o preço do activo picos para cima, e uma opção binária é um produto derivado com um tempo finito para expiração. Por outro lado, as opções binárias têm uma série de vantagens que os tornam especialmente úteis no mundo volátil do forex: o risco é limitado (mesmo se os preços dos ativos picos), colateral necessário é bastante baixo, e eles podem ser usados mesmo Em mercados planos que não são voláteis. Essas vantagens tornam as opções binárias forex dignas de consideração para o comerciante experiente que está olhando para o comércio de moedas. Alguém tem uma idéia de como compilar estaticamente qualquer arquivo de recursos diretamente no arquivo executável ou o arquivo de biblioteca compartilhada usando GCC Por exemplo Id como adicionar arquivos de imagem Que nunca mudam (e se o fizerem, eu tenho que substituir o arquivo de qualquer maneira) e não iria querer que eles mentir em torno do sistema de arquivos. Se isso é possível (e eu acho que é porque o Visual C para Windows pode fazer isso, também), como posso carregar os arquivos que são armazenados no próprio binário O executável analisar-se, encontrar o arquivo e extrair os dados de Talvez haja uma opção para o GCC que ainda não vi. Usando os motores de busca didnt realmente cuspir as coisas certas. Eu precisaria disso para trabalhar em bibliotecas compartilhadas e executáveis ELF normais. Qualquer ajuda é apreciada Dá algo como: Para compatibilidade com outro código, você pode usar fmemopen para obter um objeto FILE regular, ou, em alternativa std :: stringstream para fazer um iostream. Std :: stringstream não é ótimo para isso e você pode naturalmente usar um ponteiro em qualquer lugar você pode usar um iterador. Se você está usando isso com automake não se esqueça de configurar BUILTSOURCES adequadamente. A coisa agradável sobre fazê-lo desta maneira é: Você obtem o texto para fora, assim que pode estar no controle de versão e nos remendos sensibly É portátil e bem definido em cada plataforma respondida 1 de fevereiro em 16:04 Eu usei o objcopy (GNU binutils) Para ligar os dados binários de um arquivo foo-data. bin para a seção de dados do executável: Isto dá-lhe um arquivo de objeto foo-data. o que você pode vincular em seu executável. A interface C parece algo assim, você pode fazer coisas como Se sua arquitetura de destino tem restrições especiais a respeito de onde os dados constantes e variáveis são armazenados, ou você deseja armazenar esses dados no segmento. text para torná-lo se encaixar no mesmo tipo de memória Como seu código de programa, você pode jogar com os parâmetros objcopy um pouco mais. Respondeu Feb 1 11 at 16:36 good idea No meu caso não é muito útil. Mas isso é algo que eu realmente vou colocar na minha coleta de trechos. Obrigado por compartilhar este ndash Atmocreations Feb 1 11 at 18:04 It39s um pouco mais fácil de usar ld como o formato de saída está implícito lá, veja stackoverflow / a / 4158997/201725. Ndash Jan Hudec Mar 11 14 às 18:40 Você pode incorporar arquivos binários no executável usando ld linker. Por exemplo, se você tiver arquivo foo. bar, então você pode incorporá-lo no executável adicionando os seguintes comandos para ld Se você está invocando ld através de gcc, então você precisará adicionar - Wl Aqui --formatbinary informa o vinculador que o seguinte arquivo é Binário e --formatdefault retorna ao formato de entrada padrão (isso é útil se você especificar outros arquivos de entrada após o foo. bar). Então você pode acessar o conteúdo do seu arquivo de código: Há também um símbolo chamado binaryfoobarsize. Eu acho que é do tipo uintptrt, mas eu não o verifiquei. Recentemente tive a necessidade de incorporar um arquivo em um executável. Desde que eu estou trabalhando na linha de comando com gcc, et al e não com uma ferramenta RAD fantasia que faz tudo acontecer magicamente não era óbvio para mim como fazer isso acontecer. Um pouco de pesquisa na rede encontrou um hack para essencialmente cat para o final do executável e, em seguida, decifrar onde ele foi baseado em um monte de informações que eu não queria saber sobre. Parecia que deveria haver uma maneira melhor. E há, seu objcopy ao salvamento. Objcopy converte arquivos de objeto ou executáveis de um formato para outro. Um dos formatos que entende é binário, que é basicamente qualquer arquivo thats não em um dos outros formatos que entende. Então, você provavelmente previu a idéia: converter o arquivo que queremos incorporar em um arquivo de objeto, então ele pode simplesmente ser vinculado com o resto do nosso código. Vamos dizer que temos um nome de arquivo data. txt que queremos incorporar no nosso executável: Para converter isso em um arquivo de objeto que podemos vincular com o nosso programa que acabamos de usar objcopy para produzir um arquivo. O: Isto diz objcopy que a nossa entrada Arquivo está no formato binário, que nosso arquivo de saída deve estar no formato elf32-i386 (arquivos de objeto no x86). A opção --binary-architecture diz ao objcopy que o arquivo de saída deve ser executado em um x86. Isso é necessário para que ld aceite o arquivo para vinculação com outros arquivos para o x86. Alguém poderia pensar que especificando o formato de saída como elf32-i386 iria implicar isso, mas não. Agora que temos um arquivo de objeto, só precisamos incluí-lo quando executarmos o vinculador: Quando executamos o resultado, obtemos a oração para a saída: Claro, eu ainda não contei a história inteira, nem mostrei o main. c. Quando objcopy faz a conversão acima, adiciona alguns símbolos de vinculador ao arquivo de objeto convertido: Após a vinculação, esses símbolos especificam o início eo fim do arquivo incorporado. Os nomes dos símbolos são formados pelo prefixo binário e acrescentando início ou fim ao nome do arquivo. Se o nome do arquivo contiver quaisquer caracteres que seriam inválidos em um nome de símbolo, eles serão convertidos em sublinhados (por exemplo, data. txt torna-se datatxt). Se você obter nomes não resolvidos ao vincular usando esses símbolos, faça um hexdump - C no arquivo de objeto e olhe para o final do despejo para os nomes que objcopy escolheu. O código para realmente usar o arquivo incorporado agora deve ser razoavelmente óbvio: Uma coisa importante e sutil a ser observada é que os símbolos adicionados ao objeto são variáveis arent. Eles não contêm quaisquer dados, em vez disso, seu endereço é o seu valor. Eu declará-los como tipo char porque é conveniente para este exemplo: os dados incorporados são dados de caracteres. No entanto, você pode declará-los como qualquer coisa, como int se os dados são uma matriz de inteiros, ou como struct foobart se os dados foram qualquer matriz de foo bares. Se os dados incorporados não são uniformes, então char é provavelmente o mais conveniente: pegue seu endereço e lance o ponteiro para o tipo apropriado à medida que percorrer os dados. Respondeu Apr 1 11 at 20: 39The GNU linker ld destina-se a cobrir uma ampla gama de situações, e ser tão compatível quanto possível com outros linkers. Como resultado, você tem muitas opções para controlar seu comportamento. Aqui está um resumo das opções que você pode usar na linha de comando ld: Esta infinidade de opções de linha de comando pode parecer intimidante, mas na prática algumas delas são usadas em qualquer contexto específico. Por exemplo, um uso freqüente de ld é ligar arquivos de objeto Unix padrão em um sistema Unix padrão, suportado. Em tal sistema, para ligar um arquivo hello. o. Isto diz ao ld para produzir um arquivo chamado saída como resultado da vinculação do arquivo /lib/crt0.o com hello. o e da biblioteca libc. a. Que virá dos diretórios de pesquisa padrão. (Consulte a discussão da opção - l abaixo.) As opções de linha de comando para ld podem ser especificadas em qualquer ordem e podem ser repetidas à vontade. Repetir a maioria das opções com um argumento diferente não terá mais efeito ou substituirá as ocorrências anteriores (aquelas mais à esquerda na linha de comando) dessa opção. As exceções - que podem ser usadas mais de uma vez - são - A. - b (ou seu sinônimo - format), - defsym. - EU. - eu. - R. - você. E - (ou seu sinônimo --start-group). A lista de arquivos de objeto a serem ligados, mostrados como objfile, pode seguir, preceder ou ser misturado com as opções de linha de comando, exceto que um argumento objfile não pode Ser colocado entre uma opção e seu argumento. Normalmente, o vinculador é chamado com pelo menos um arquivo de objeto, mas você pode especificar outras formas de arquivos de entrada binária usando-l. - R. Todos são especificados, o vinculador não produz qualquer saída e emite a mensagem Sem arquivos de entrada. Se o vinculador não pode reconhecer o formato de um arquivo de objeto, ele assumirá que é um script de vinculação. Um script especificado desta maneira aumenta O script de vinculador principal usado para o link (ou o script de vinculador padrão ou aquele especificado usando - T). Esse recurso permite que o vinculador para vincular um arquivo que parece ser um objeto ou um arquivo, mas na verdade apenas define algum símbolo Valores, ou usa INPUT ou GROUP para carregar outros objetos Consulte a seção Command Language. Para opções cujos nomes são uma única letra, os argumentos de opção devem seguir a letra da opção sem intervir em espaços em branco ou ser dados como argumentos separados imediatamente após a opção que os requer. Para opções cujos nomes são múltiplas letras, um traço ou dois podem preceder o nome da opção, por exemplo, --oformat e - formato são equivalentes. Os argumentos para opções de várias letras devem ser separados do nome da opção por um sinal de igual ou ser dados como argumentos separados imediatamente após a opção que os requer. Por exemplo, --oformat srec e --oformatsrec são equivalentes. São aceitas abreviaturas únicas dos nomes das opções de várias letras. - b input-format ld pode ser configurado para suportar mais de um tipo de arquivo de objeto. Se seu ld estiver configurado desta maneira, você pode usar a opção - b para especificar o formato binário para os arquivos de objetos de entrada que seguem esta opção na linha de comando. Mesmo quando o ld está configurado para suportar formatos de objetos alternativos, normalmente não é necessário especificar isso, pois ld deve ser configurado para esperar como formato de entrada padrão o formato mais comum em cada máquina. Input-format é uma string de texto, o nome de um formato particular suportado pelas bibliotecas BFD. (Você pode listar os formatos binários disponíveis com objdump - i.) - format input-format tem o mesmo efeito, como faz o comando de script TARGET. Consulte a seção BFD. Você pode usar essa opção se estiver vinculando arquivos com um formato binário incomum. Você também pode usar - b para alternar formatos de forma explícita (ao vincular arquivos de objetos de diferentes formatos), incluindo - b input-format antes de cada grupo de arquivos de objeto em um formato específico. O formato padrão é obtido a partir da variável de ambiente GNUTARGET. Você também pode definir o formato de entrada de um script, usando o comando TARGET, veja a seção Comandos de Opção. - Bstatic Não vincule contra bibliotecas compartilhadas. Isso só é significativo em plataformas para as quais bibliotecas compartilhadas são suportadas. - Link dinâmico contra bibliotecas dinâmicas. Isso só é significativo em plataformas para as quais bibliotecas compartilhadas são suportadas. Esta opção é normalmente a predefinição em tais plataformas. - Bsymbolic Ao criar uma biblioteca compartilhada, vincular referências a símbolos globais para a definição dentro da biblioteca compartilhada, se houver. Normalmente, é possível que um programa vinculado a uma biblioteca compartilhada substitua a definição na biblioteca compartilhada. Esta opção só é significativa em plataformas ELF que suportam bibliotecas compartilhadas. - c MRI-commandfile Para compatibilidade com vinculadores produzidos por MRI, ld aceita arquivos de script escritos em uma linguagem de comando restrita e alternativa, descrita na seção MRI Compatible Script Files. Introduza arquivos de script MRI com a opção - c use a opção - T para executar scripts de vinculadores escritos na linguagem de scripting ld de uso geral. Se MRI-cmdfile não existir, ld procurará nos diretórios especificados por quaisquer opções - L. - d - dc - dp Essas três opções são equivalentes são suportados vários formulários para compatibilidade com outros vinculadores. Eles atribuem espaço a símbolos comuns mesmo se um arquivo de saída relocável é especificado (com - r). O comando de script FORCECOMMONALLOCATION tem o mesmo efeito. Consulte a seção Comandos de opção. - defsym expressão de símbolo Crie um símbolo global no arquivo de saída, contendo o endereço absoluto dado por expressão. Você pode usar essa opção quantas vezes forem necessárias para definir vários símbolos na linha de comando. Uma forma limitada de aritmética é suportada para a expressão neste contexto: você pode dar uma constante hexadecimal ou o nome de um símbolo existente, ou usar e - para adicionar ou subtrair constantes hexadecimais ou símbolos. Se você precisar de expressões mais elaboradas, considere usar a linguagem de comando do vinculador de um script (consulte a seção Atribuição: Definindo Símbolos). Nota: não deve haver espaço em branco entre o símbolo. O sinal de igual () e a expressão. - embedded-relocs Essa opção só é significativa quando se vincula código MIPS incorporado PIC, gerado pela opção - membedded-pic para o compilador GNU e assembler. Faz com que o vinculador crie uma tabela que pode ser usada em tempo de execução para realocar quaisquer dados que foi inicializado estaticamente para valores de ponteiro. Consulte o código em testsuite / ld-empic para obter detalhes. - e entry Use a entrada como o símbolo explícito para iniciar a execução do seu programa, em vez do ponto de entrada padrão. Consulte a seção O ponto de entrada. Para uma discussão de padrões e outras formas de especificar o ponto de entrada. - F - F formato Ignorado. Alguns vinculadores mais antigos usaram essa opção em toda uma cadeia de ferramentas de compilação para especificar o formato de arquivo de objeto para os arquivos de objetos de entrada e de saída. Os mecanismos ld usam para essa finalidade (as opções - b ou - format para arquivos de entrada, a opção - formato ou o comando TARGET em scripts linker para arquivos de saída, a variável de ambiente GNUTARGET) são mais flexíveis, mas ld aceita a opção - F para Compatibilidade com scripts escritos para chamar o vinculador antigo. - format input-format Sinônimo de - b input-format. - g Ignorado. Fornecido para a compatibilidade com outras ferramentas. - G value - G value Define o tamanho máximo de objetos a serem otimizados usando o GP register para tamanho sob MIPS ECOFF. Ignorado para outros formatos de arquivo de objeto. - help Imprime um resumo das opções da linha de comando na saída e saída padrão. - i Executa um link incremental (igual à opção - r). - l ar Adiciona um arquivo archive à lista de arquivos a vincular. Esta opção pode ser usada qualquer número de vezes. Ld procurará sua lista de caminho para ocorrências de lib ar. a para cada arquivo especificado. - L searchdir - L searchdir Adicionar path searchdir à lista de caminhos que ld procurará por bibliotecas de arquivo e scripts de controle ld. Você pode usar esta opção qualquer número de vezes. Os diretórios são pesquisados na ordem em que são especificados na linha de comando. Os diretórios especificados na linha de comando são pesquisados antes dos diretórios padrão. Todas as opções - L se aplicam a todas as opções - l, independentemente da ordem em que as opções aparecem. Os caminhos também podem ser especificados em um script de link com o comando SEARCHDIR. Os diretórios especificados desta maneira são pesquisados no ponto em que o script de vinculador aparece na linha de comando. - M Imprimir (para a saída padrão) um mapa de link - informações de diagnóstico sobre onde os símbolos são mapeados por ld. E informações sobre alocação global de armazenamento comum. - Map mapfile Imprimir para o arquivo mapfile a link map - informações de diagnóstico sobre onde os símbolos são mapeados por ld. E informações sobre alocação global de armazenamento comum. - m emulação - m emulação Emule o emulação linker. Você pode listar as emulações disponíveis com as opções --verbose ou - V. O padrão depende de como seu ld foi configurado. - N Defina as seções de texto e dados para que possam ser lidas e graváveis. Além disso, não página-alinhar o segmento de dados. Se o formato de saída suporta números mágicos de estilo Unix, marque a saída como OMAGIC. - n Defina o segmento de texto a ser somente leitura e marque a saída como NMAGIC se possível. - noinhibit-exec Retenha o arquivo de saída executável sempre que ele for ainda utilizável. Normalmente, o vinculador não produzirá um arquivo de saída se encontrar erros durante o processo de link que ele sai sem escrever um arquivo de saída quando ele emite qualquer erro. - no-keep-memory ld normalmente otimiza a velocidade sobre o uso de memória, colocando em cache as tabelas de símbolos dos arquivos de entrada na memória. Essa opção informa ld para otimizar o uso da memória, relendo as tabelas de símbolos conforme necessário. Isso pode ser necessário se o ld ficar sem espaço de memória enquanto estiver vinculando um arquivo executável grande. - o output Use saída como o nome para o programa produzido por ld se essa opção não for especificada, o nome a. out é usado por padrão. O comando de script OUTPUT também pode especificar o nome do arquivo de saída. - formato saída-formato ld pode ser configurado para suportar mais de um tipo de arquivo de objeto. Se seu ld estiver configurado desta maneira, você pode usar a opção - oformat para especificar o formato binário para o arquivo de objeto de saída. Mesmo quando o ld está configurado para suportar formatos de objetos alternativos, normalmente não é necessário especificar isso, pois ld deve ser configurado para produzir como formato de saída padrão o formato mais comum em cada máquina. Output-format é uma string de texto, o nome de um formato particular suportado pelas bibliotecas BFD. (Você pode listar os formatos binários disponíveis com objdump - i.) O comando de script OUTPUTFORMAT também pode especificar o formato de saída, mas essa opção substitui-lo. Consulte a seção BFD. - R filename Ler os nomes dos símbolos e seus endereços a partir do nome do arquivo. Mas não realocá-lo ou incluí-lo na saída. Isso permite que seu arquivo de saída se refira simbolicamente a locais absolutos de memória definidos em outros programas. - relax Uma opção com efeitos dependentes da máquina. Em algumas plataformas, a opção - relax executa otimizações globais que se tornam possíveis quando o vinculador resolve o endereçamento no programa, como relaxar modos de endereço e sintetizar novas instruções no arquivo de objeto de saída. - retain-symbols-file filename Retenha apenas os símbolos listados no arquivo filename. Descartando todos os outros. Filename é simplesmente um arquivo simples, com um nome de símbolo por linha. Essa opção é especialmente útil em ambientes onde uma grande tabela de símbolos global é acumulada gradualmente, para economizar memória de tempo de execução. - retain-symbols-file não descarta símbolos indefinidos ou símbolos necessários para relocações. Você só pode especificar - retain-symbols-file uma vez na linha de comando. Substitui-s e - S. - r Gerar saída relocável - ou seja. Gerar um arquivo de saída que por sua vez pode servir como entrada para ld. Isso é muitas vezes chamado de ligação parcial. Como um efeito colateral, em ambientes que suportam números mágicos padrão do Unix, essa opção também define o número mágico dos arquivos de saída para OMAGIC. Se essa opção não for especificada, um arquivo absoluto será produzido. Ao vincular programas C, esta opção não resolverá referências a construtores para fazer isso, use - Ur. Esta opção faz a mesma coisa que - i. - S Omitir informações do símbolo depurador (mas não todos os símbolos) do arquivo de saída. - s Omite todas as informações de símbolo do arquivo de saída. - shared Criar uma biblioteca compartilhada. Atualmente, isso só é suportado em plataformas ELF e SunOS. No SunOS, o vinculador criará automaticamente uma biblioteca compartilhada se a opção - e não for usada e houver símbolos indefinidos no link. - sort-common Normalmente, quando ld coloca os símbolos comuns globais nas seções de saída apropriadas, classifica-os por tamanho. Primeiro vêm todos os símbolos de um byte, depois todos os dois bytes, depois todos os quatro bytes, e depois tudo o resto. Isso é para evitar aberturas entre símbolos devido a restrições de alinhamento. Esta opção desabilita essa classificação. - split-by-reloc count Trys para cria seções extras no arquivo de saída para que nenhuma seção de saída única no arquivo contém mais do que contagem relocações. Isso é útil quando se gera um grande relocável para download em determinados kernels em tempo real com o formato de arquivo de objeto COFF, já que o COFF não pode representar mais de 65535 deslocalizações em uma única seção. Observe que isso falhará ao trabalhar com formatos de arquivo de objeto que não suportam seções arbitrárias. O linker não dividirá seções de entrada individuais para redistribuição, portanto, se uma única seção de entrada contém mais do que contagem de relocações, uma seção de saída conterá muitas deslocalizações. - split-by-file Similar a - split-by-reloc, mas cria uma nova seção de saída para cada arquivo de entrada. - stats Compute e exiba estatísticas sobre a operação do vinculador, como tempo de execução e uso de memória. - Tbss org - Tdata org - Ttext org Use org como o endereço inicial para - respectivamente - o bss. dados. Ou o segmento de texto do arquivo de saída. Org deve ser um único inteiro hexadecimal para compatibilidade com outros vinculadores, você pode omitir o 0x principal normalmente associado com valores hexadecimais. - T commandfile - T commandfile Ler os comandos do link do arquivo commandfile. Esses comandos substituem o script de link padrão do ld s (em vez de adicionar a ele), então commandfile deve especificar tudo o necessário para descrever o formato de destino. Consulte a seção Linguagem de Comando. Se commandfile não existir, ld procura-lo nos diretórios especificados por qualquer precedente - L opções. Várias opções - T acumulam. - t Imprime os nomes dos arquivos de entrada conforme ld os processa. - traditional-format Para alguns alvos, a saída de ld é diferente em alguns aspectos da saída de algum vinculador existente. Esta opção solicita ld para usar o formato tradicional em vez disso. Por exemplo, no SunOS, ld combina entradas duplicadas na tabela de cadeias de símbolos. Isso pode reduzir o tamanho de um arquivo de saída com informações de depuração em mais de 30 por cento. Infelizmente, o programa dbx do SunOS não consegue ler o programa resultante (o gdb não tem problemas). O parâmetro de formato tradicional informa ld para não combinar entradas duplicadas. - u símbolo Força símbolo a ser inserido no arquivo de saída como um símbolo indefinido. Isso pode, por exemplo, ativar a vinculação de módulos adicionais de bibliotecas padrão. - u pode ser repetido com argumentos de opção diferentes para inserir símbolos adicionais indefinidos. - Ur Para qualquer outra coisa que não programas C, esta opção é equivalente a - r. Ele gera saída relocável - i. e. Um arquivo de saída que por sua vez pode servir como entrada para ld. Ao ligar programas em C, - Ur resolve referências a construtores, ao contrário de - r. Ele não funciona para usar - Ur em arquivos que foram eles mesmos vinculados com - Ur uma vez que a tabela do construtor foi construída, ele não pode ser adicionado a. Use - Ur apenas para o último link parcial e - r para os outros. --verbose Exibe o número da versão para ld e lista as emulações de vinculador suportadas. Exibe quais arquivos de entrada podem e não podem ser abertos. - v - V Exibe o número da versão para ld. A opção - V também lista as emulações suportadas. - version Exibe o número da versão para ld e sai. - warn-common Avisa quando um símbolo comum é combinado com outro símbolo comum ou com uma definição de símbolo. Unix linkers permitir esta prática um pouco desleixada, mas vinculadores em alguns outros sistemas operacionais não. Esta opção permite-lhe encontrar possíveis problemas de combinar símbolos globais. Infelizmente, algumas bibliotecas C usam essa prática, para que você possa receber alguns avisos sobre símbolos nas bibliotecas, bem como em seus programas. Há três tipos de símbolos globais, ilustrados aqui por exemplos C: int i 1 Uma definição, que vai na seção de dados inicializada do arquivo de saída. Extern int i Uma referência indefinida, que não aloca espaço. Deve haver uma definição ou um símbolo comum para a variável em algum lugar. Int i Um símbolo comum. Se houver apenas (um ou mais) símbolos comuns para uma variável, ele vai na área de dados não inicializada do arquivo de saída. O vinculador mescla vários símbolos comuns para a mesma variável em um único símbolo. Se eles são de tamanhos diferentes, ele escolhe o maior tamanho. O vinculador transforma um símbolo comum em uma declaração, se houver uma definição da mesma variável. A opção - warn-common pode produzir cinco tipos de avisos. Cada aviso consiste em um par de linhas: a primeira descreve o símbolo que acabamos de encontrar e a segunda descreve o símbolo anterior encontrado com o mesmo nome. Um ou ambos os dois símbolos serão um símbolo comum. Transformando um símbolo comum em uma referência, porque já existe uma definição para o símbolo. Transformando um símbolo comum em uma referência, porque uma definição posterior para o símbolo é encontrada. Este é o mesmo que o caso anterior, exceto que os símbolos são encontrados em uma ordem diferente. Mesclando um símbolo comum com um símbolo comum do mesmo tamanho anterior. Mesclando um símbolo comum com um símbolo comum anterior maior. Mesclando um símbolo comum com um símbolo comum anterior menor. Este é o mesmo que o caso anterior, exceto que os símbolos são encontrados em uma ordem diferente. - warn-constructors Avisar se qualquer construtores globais são usados. Isso é útil somente para alguns formatos de arquivo de objeto. Para formatos como COFF ou ELF, o vinculador não pode detectar o uso de construtores globais. - warn-once Apenas warn uma vez para cada símbolo indefinido, em vez de uma vez por módulo que se refere a ele. Para cada arquivo mencionado na linha de comando, inclua todos os arquivos de objeto no arquivo no link, em vez de pesquisar o arquivo para os arquivos de objeto necessários. Isso normalmente é usado para transformar um arquivo archive em uma biblioteca compartilhada, forçando cada objeto a ser incluído na biblioteca compartilhada resultante. - X Exclui todos os símbolos locais temporários. Para a maioria dos alvos, todos os símbolos locais que começam com L. - x Apagar todos os símbolos locais. - y símbolo Imprime o nome de cada arquivo vinculado no qual o símbolo aparece. Esta opção pode ser dada qualquer número de vezes. Em muitos sistemas é necessário antecipar um sublinhado. Esta opção é útil quando você tem um símbolo indefinido em seu link, mas não sabe de onde a referência está vindo. - (archives -) --start-group archives --end-group Os arquivos devem ser uma lista de arquivos de arquivo. Eles podem ser nomes de arquivos explícitos ou opções - l. Os arquivos especificados são pesquisados repetidamente até que nenhuma nova referência indefinida seja criada. Normalmente, um arquivo é pesquisado apenas uma vez na ordem em que é especificado na linha de comando. Se um símbolo nesse arquivo é necessário para resolver um símbolo indefinido referido por um objeto em um arquivo que aparece mais tarde na linha de comando, o vinculador não seria capaz de resolver essa referência. Agrupando os arquivos, todos eles serão pesquisados repetidamente até que todas as referências possíveis sejam resolvidas. A utilização desta opção tem um custo de desempenho significativo. É melhor usá-lo somente quando houver referências circulares inevitáveis entre dois ou mais arquivos. Vá para o primeiro. anterior. Próximo. Última seção, tabela de conteúdo. A linguagem de comando fornece controle explícito sobre o processo de link, permitindo a especificação completa do mapeamento entre os arquivos de entrada dos vinculadores e sua saída. Ele controla: arquivos de entrada formatos de arquivo endereços de layout de arquivo de saída de seções posicionamento de blocos comuns Você pode fornecer um arquivo de comando (também conhecido como um script de link) para o vinculador, explicitamente através da opção - T ou implicitamente como um arquivo comum. Se o vinculador abre um arquivo que não pode reconhecer como um objeto suportado ou formato de arquivo, ele relata um erro. A linguagem de comando do ld é uma coleção de instruções, algumas são palavras-chave simples definindo uma opção particular, algumas são usadas para selecionar e agrupar arquivos de entrada ou arquivos de saída de nomes e dois tipos de instruções têm um impacto fundamental e penetrante no processo de vinculação. O comando mais fundamental da linguagem de comando do ld é o comando SECTIONS (ver seção Especificando Seções de Saída). Cada script de comando significativo deve ter um comando SECTIONS: especifica uma imagem do layout dos arquivos de saída, em vários graus de detalhe. Nenhum outro comando é exigido em todos os casos. O comando MEMORY complementa SECTIONS descrevendo a memória disponível na arquitetura de destino. Este comando é opcional se você não usar um comando MEMORY, ld assume que a memória suficiente está disponível em um bloco contíguo para toda a saída. Consulte a seção Layout da memória. Você pode incluir comentários em scripts de vinculadores exatamente como em C: delimitado por / e /. Como em C, os comentários são sintaticamente equivalentes a espaços em branco. Muitos comandos úteis envolvem expressões aritméticas. A sintaxe para expressões na linguagem de comando é idêntica à das expressões C, com as seguintes características: Todas as expressões avaliadas como inteiros e são de tipo longo ou não assinado. Todas as constantes são inteiros. Todos os operadores aritméticos C são fornecidos. Você pode fazer referência, definir e criar variáveis globais. Você pode chamar funções especiais incorporadas. Inteiros. Símbolos de números inteiros. Símbolo Nomes Local Contador. Os Operadores de Contador de Localização. Avaliação de Operadores. Atribuição de Avaliação. Atribuição: Definição de símbolos Funções aritméticas. Funções incorporadas Um inteiro octal é 0 seguido por zero ou mais dos dígitos octal (01234567). Um inteiro decimal começa com um dígito diferente de zero seguido por zero ou mais dígitos (0123456789). Um inteiro hexadecimal é 0x ou 0X seguido por um ou mais dígitos hexadecimais escolhidos de 0123456789abcdefABCDEF. Para escrever um inteiro negativo, use o operador prefixo - veja a seção Operadores. Além disso, os sufixos K e M podem ser usados para escalar uma constante, respectivamente. Por exemplo, os seguintes todos se referem à mesma quantidade: A menos que sejam citados, os nomes de símbolos começam com uma letra, sublinhado ou ponto e podem incluir letras, sublinhados, dígitos, pontos e hifens. Nomes de símbolos não cotados não devem entrar em conflito com quaisquer palavras-chave. Você pode especificar um símbolo que contenha caracteres ímpares ou tenha o mesmo nome de uma palavra-chave, cercando o nome do símbolo entre aspas: Uma vez que os símbolos podem conter muitos caracteres não alfabéticos, é mais seguro delimitar símbolos com espaços. Por exemplo, A-B é um símbolo, enquanto A-B é uma expressão envolvendo subtração. O ponto especial variável linker. Sempre contém o contador de localização de saída atual. Desde o. Sempre se refere a um local em uma seção de saída, ele deve sempre aparecer em uma expressão dentro de um comando SECTIONS. O. Pode aparecer em qualquer lugar que um símbolo comum é permitido em uma expressão, mas suas atribuições têm um efeito colateral. Atribuir um valor ao. O contador de localização será movido. Isso pode ser usado para criar furos na seção de saída. O contador de localização pode nunca ser movido para trás. No exemplo anterior, file1 está localizado no início da seção de saída, então há um intervalo de 1000 bytes. Em seguida, file2 aparece, também com um intervalo de 1000 bytes antes de file3 é carregado. A notação 0x1234 especifica quais dados gravar nas lacunas (consulte a seção Atributos de Seção Opcionais). O vinculador usa avaliação preguiçosa para expressões que só calcula uma expressão quando absolutamente necessário. O vinculador precisa do valor do endereço de início e os comprimentos de regiões de memória, para fazer qualquer ligação a todos esses valores são calculados o mais rapidamente possível quando o vinculador lê no arquivo de comando. No entanto, outros valores (como valores de símbolo) não são conhecidos ou necessários até após a alocação de armazenamento. Esses valores são avaliados posteriormente, quando outras informações (como os tamanhos das seções de saída) estão disponíveis para uso na expressão de atribuição de símbolos. Você pode criar símbolos globais e atribuir valores (endereços) a símbolos globais, usando qualquer um dos operadores de atribuição C: símbolo de expressão símbolo símbolo de expressão símbolo de expressão expressão símbolo expressão / expressão Duas coisas distinguem atribuição de outros operadores em expressões ld. A atribuição só pode ser usada na raiz de uma expressão ab3 é permitida, mas ab3 é um erro. Você deve colocar um ponto e vírgula () no final de uma declaração de atribuição. As instruções de atribuição podem aparecer: como comandos em seu próprio direito em um script ld ou como instruções independentes dentro de um comando SECTIONS ou como parte do conteúdo de uma definição de seção em um comando SECTIONS. Os dois primeiros casos são equivalentes em efeito - ambos definem um símbolo com um endereço absoluto. O último caso define um símbolo cujo endereço é relativo a uma seção específica (veja seção Especificando Seções de Saída). When a linker expression is evaluated and assigned to a variable, it is given either an absolute or a relocatable type. An absolute expression type is one in which the symbol contains the value that it will have in the output file a relocatable expression type is one in which the value is expressed as a fixed offset from the base of a section. The type of the expression is controlled by its position in the script file. A symbol assigned within a section definition is created relative to the base of the section a symbol assigned in any other place is created as an absolute symbol. Since a symbol created within a section definition is relative to the base of the section, it will remain relocatable if relocatable output is requested. A symbol may be created with an absolute value even when assigned to within a section definition by using the absolute assignment function ABSOLUTE. For example, to create an absolute symbol whose address is the last byte of an output section named. data. The linker tries to put off the evaluation of an assignment until all the terms in the source expression are known (see section Evaluation ). For instance, the sizes of sections cannot be known until after allocation, so assignments dependent upon these are not performed until after allocation. Some expressions, such as those depending upon the location counter dot . . must be evaluated during allocation. If the result of an expression is required, but the value is not available, then an error results. For example, a script like the following will cause the error message Non constant expression for initial address . In some cases, it is desirable for a linker script to define a symbol only if it is referenced, and only if it is not defined by any object included in the link. For example, traditional linkers defined the symbol etext. However, ANSI C requires that the user be able to use etext as a function name without encountering an error. The PROVIDE keyword may be used to define a symbol, such as etext. only if it is referenced but not defined. The syntax is PROVIDE( symbol expression ). The command language includes a number of built-in functions for use in link script expressions. ABSOLUTE( exp ) Return the absolute (non-relocatable, as opposed to non-negative) value of the expression exp. Primarily useful to assign an absolute value to a symbol within a section definition, where symbol values are normally section-relative. ADDR( section ) Return the absolute address of the named section. Your script must previously have defined the location of that section. In the following example, symbol1 and symbol2 are assigned identical values: ALIGN( exp ) Return the result of the current location counter (. ) aligned to the next exp boundary. exp must be an expression whose value is a power of two. This is equivalent to ALIGN doesnt change the value of the location counter--it just does arithmetic on it. As an example, to align the output. data section to the next 0x2000 byte boundary after the preceding section and to set a variable within the section to the next 0x8000 boundary after the input sections: The first use of ALIGN in this example specifies the location of a section because it is used as the optional start attribute of a section definition (see section Optional Section Attributes ). The second use simply defines the value of a variable. The built-in NEXT is closely related to ALIGN. DEFINED( symbol ) Return 1 if symbol is in the linker global symbol table and is defined, otherwise return 0. You can use this function to provide default values for symbols. For example, the following command-file fragment shows how to set a global symbol begin to the first location in the. text section--but if a symbol called begin already existed, its value is preserved: NEXT( exp ) Return the next unallocated address that is a multiple of exp. This function is closely related to ALIGN( exp ) unless you use the MEMORY command to define discontinuous memory for the output file, the two functions are equivalent. SIZEOF( section ) Return the size in bytes of the named section. if that section has been allocated. In the following example, symbol1 and symbol2 are assigned identical values: SIZEOFHEADERS sizeofheaders Return the size in bytes of the output files headers. You can use this number as the start address of the first section, if you choose, to facilitate paging. The linkers default configuration permits allocation of all available memory. You can override this configuration by using the MEMORY command. The MEMORY command describes the location and size of blocks of memory in the target. By using it carefully, you can describe which memory regions may be used by the linker, and which memory regions it must avoid. The linker does not shuffle sections to fit into the available regions, but does move the requested sections into the correct regions and issue errors when the regions become too full. A command file may contain at most one use of the MEMORY command however, you can define as many blocks of memory within it as you wish. The syntax is: name is a name used internally by the linker to refer to the region. Any symbol name may be used. The region names are stored in a separate name space, and will not conflict with symbols, file names or section names. Use distinct names to specify multiple regions. ( attr ) is an optional list of attributes, permitted for compatibility with the AT38T linker but not used by ld beyond checking that the attribute list is valid. Valid attribute lists must be made up of the characters LIRWX . If you omit the attribute list, you may omit the parentheses around it as well. origin is the start address of the region in physical memory. It is an expression that must evaluate to a constant before memory allocation is performed. The keyword ORIGIN may be abbreviated to org or o (but not, for example, ORG ). len is the size in bytes of the region (an expression). The keyword LENGTH may be abbreviated to len or l. For example, to specify that memory has two regions available for allocation--one starting at 0 for 256 kilobytes, and the other starting at 0x40000000 for four megabytes: Once you have defined a region of memory named mem. you can direct specific output sections there by using a command ending in 62 mem within the SECTIONS command (see section Optional Section Attributes ). If the combined output sections directed to a region are too big for the region, the linker will issue an error message. The SECTIONS command controls exactly where input sections are placed into output sections, their order in the output file, and to which output sections they are allocated. You may use at most one SECTIONS command in a script file, but you can have as many statements within it as you wish. Statements within the SECTIONS command can do one of three things: define the entry point assign a value to a symbol describe the placement of a named output section, and which input sections go into it. You can also use the first two operations--defining the entry point and defining symbols--outside the SECTIONS command: see section The Entry Point. and see section Assignment: Defining Symbols. They are permitted here as well for your convenience in reading the script, so that symbols and the entry point can be defined at meaningful points in your output-file layout. If you do not use a SECTIONS command, the linker places each input section into an identically named output section in the order that the sections are first encountered in the input files. If all input sections are present in the first file, for example, the order of sections in the output file will match the order in the first input file. The most frequently used statement in the SECTIONS command is the section definition . which specifies the properties of an output section: its location, alignment, contents, fill pattern, and target memory region. Most of these specifications are optional the simplest form of a section definition is secname is the name of the output section, and contents a specification of what goes there--for example, a list of input files or sections of input files (see section Section Placement ). As you might assume, the whitespace shown is optional. You do need the colon : and the braces . Contudo. secname must meet the constraints of your output format. In formats which only support a limited number of sections, such as a. out. the name must be one of the names supported by the format ( a. out. for example, allows only. text. data or. bss ). If the output format supports any number of sections, but with numbers and not names (as is the case for Oasys), the name should be supplied as a quoted numeric string. A section name may consist of any sequence of characters, but any name which does not conform to the standard ld symbol name syntax must be quoted. See section Symbol Names. The linker will not create output sections which do not have any contents. This is for convenience when referring to input sections that may or may not exist. For example, will only create a. foo section in the output file if there is a. foo section in at least one input file. In a section definition, you can specify the contents of an output section by listing particular input files, by listing particular input-file sections, or by a combination of the two. You can also place arbitrary data in the section, and define symbols relative to the beginning of the section. The contents of a section definition may include any of the following kinds of statement. You can include as many of these as you like in a single section definition, separated from one another by whitespace. filename You may simply name a particular input file to be placed in the current output section all sections from that file are placed in the current section definition. If the file name has already been mentioned in another section definition, with an explicit section name list, then only those sections which have not yet been allocated are used. To specify a list of particular files by name: The example also illustrates that multiple statements can be included in the contents of a section definition, since each file name is a separate statement. filename ( section ) filename ( section. section. ) filename ( section section. ) You can name one or more sections from your input files, for insertion in the current output section. If you wish to specify a list of input-file sections inside the parentheses, you may separate the section names by either commas or whitespace. ( section ) ( section. section. ) ( section section. ) Instead of explicitly naming particular input files in a link control script, you can refer to all files from the ld command line: use instead of a particular file name before the parenthesized input-file section list. If you have already explicitly included some files by name, refers to all remaining files--those whose places in the output file have not yet been defined. For example, to copy sections 1 through 4 from an Oasys file into the. text section of an a. out file, and sections 13 and 14 into the. data section: section. used to be accepted as an alternate way to specify named sections from all unallocated input files. Because some operating systems (VMS) allow brackets in file names, that notation is no longer supported. filename ( COMMON ) ( COMMON ) Specify where in your output file to place uninitialized data with this notation. (COMMON) by itself refers to all uninitialized data from all input files (so far as it is not yet allocated) filename (COMMON) refers to uninitialized data from a particular file. Both are special cases of the general mechanisms for specifying where to place input-file sections: ld permits you to refer to uninitialized data as if it were in an input-file section named COMMON. regardless of the input files format. For example, the following command script arranges the output file into three consecutive sections, named. text. data. and. bss. taking the input for each from the correspondingly named sections of all the input files: The following example reads all of the sections from file all. o and places them at the start of output section outputa which starts at location 0x10000. All of section. input1 from file foo. o follows immediately, in the same output section. All of section. input2 from foo. o goes into output section outputb. followed by section. input1 from foo1.o. All of the remaining. input1 and. input2 sections from any files are written to output section outputc. The foregoing statements arrange, in your output file, data originating from your input files. You can also place data directly in an output section from the link command script. Most of these additional statements involve expressions see section Expressions. Although these statements are shown separately here for ease of presentation, no such segregation is needed within a section definition in the SECTIONS command you can intermix them freely with any of the statements weve just described. CREATEOBJECTSYMBOLS Create a symbol for each input file in the current section, set to the address of the first byte of data written from that input file. For instance, with a. out files it is conventional to have a symbol for each input file. You can accomplish this by defining the output. text section as follows: If sample. ld is a file containing this script, and a. o. b. o. c. o. and d. o are four input files with contents like the following--- ld - M - T sample. ld a. o b. o c. o d. o would create a map like this, containing symbols matching the object file names: symbol expression symbol f expression symbol is any symbol name (see section Symbol Names ). f refers to any of the operators 38 - / which combine arithmetic and assignment. When you assign a value to a symbol within a particular section definition, the value is relative to the beginning of the section (see section Assignment: Defining Symbols ). If you write abs and rel do not have the same value rel has the same value as abs2. BYTE( expression ) SHORT( expression ) LONG( expression ) QUAD( expression ) By including one of these four statements in a section definition, you can explicitly place one, two, four, or eight bytes (respectively) at the current address of that section. QUAD is only supported when using a 64 bit host or target. Multiple-byte quantities are represented in whatever byte order is appropriate for the output file format (see section BFD ). FILL( expression ) Specify the fill pattern for the current section. Any otherwise unspecified regions of memory within the section (for example, regions you skip over by assigning a new value to the location counter . ) are filled with the two least significant bytes from the expression argument. A FILL statement covers memory locations after the point it occurs in the section definition by including more than one FILL statement, you can have different fill patterns in different parts of an output section. Here is the full syntax of a section definition, including all the optional portions: secname and contents are required. See section Section Definitions. and see section Section Placement for details on contents. The remaining elements--- start. BLOCK( align). (NOLOAD). AT ( ldadr ). 62 region. and fill ---are all optional. start You can force the output section to be loaded at a specified address by specifying start immediately following the section name. start can be represented as any expression. The following example generates section output at location 0x40000000. BLOCK( align ) You can include BLOCK() specification to advance the location counter. prior to the beginning of the section, so that the section will begin at the specified alignment. align is an expression. (NOLOAD) Use (NOLOAD) to prevent a section from being loaded into memory each time it is accessed. For example, in the script sample below, the ROM segment is addressed at memory location 0 and does not need to be loaded into each object file: AT ( ldadr ) The expression ldadr that follows the AT keyword specifies the load address of the section. The default (if you do not use the AT keyword) is to make the load address the same as the relocation address. This feature is designed to make it easy to build a ROM image. For example, this SECTIONS definition creates two output sections: one called. text. which starts at 0x1000. and one called. mdata. which is loaded at the end of the. text section even though its relocation address is 0x2000. The symbol data is defined with the value 0x2000. The run-time initialization code (for C programs, usually crt0 ) for use with a ROM generated this way has to include something like the following, to copy the initialized data from the ROM image to its runtime address: 62 region Assign this section to a previously defined region of memory. See section Memory Layout. fill Including fill in a section definition specifies the initial fill value for that section. You may use any expression to specify fill. Any unallocated holes in the current output section when written to the output file will be filled with the two least significant bytes of the value, repeated as necessary. You can also change the fill value with a FILL statement in the contents of a section definition. The linker command language includes a command specifically for defining the first executable instruction in an output file (its entry point ). Its argument is a symbol name: Like symbol assignments, the ENTRY command may be placed either as an independent command in the command file, or among the section definitions within the SECTIONS command--whatever makes the most sense for your layout. ENTRY is only one of several ways of choosing the entry point. You may indicate it in any of the following ways (shown in descending order of priority: methods higher in the list override methods lower down). the - e entry command-line option the ENTRY( symbol ) command in a linker control script the value of the symbol start. if present the address of the first byte of the. text section, if present The address 0. For example, you can use these rules to generate an entry point with an assignment statement: if no symbol start is defined within your input files, you can simply define it, assigning it an appropriate value--- The example shows an absolute address, but you can use any expression. For example, if your input object files use some other symbol-name convention for the entry point, you can just assign the value of whatever symbol contains the start address to start. The command language includes a number of other commands that you can use for specialized purposes. They are similar in purpose to command-line options. CONSTRUCTORS This command ties up C style constructor and destructor records. The details of the constructor representation vary from one object format to another, but usually lists of constructors and destructors appear as special sections. The CONSTRUCTORS command specifies where the linker is to place the data from these sections, relative to the rest of the linked output. Constructor data is marked by the symbol CTORLIST at the start, and CTORLISTEND at the end destructor data is bracketed similarly, between DTORLIST and DTORLISTEND. (The compiler must arrange to actually run this code GNU C calls constructors from a subroutine main. which it inserts automatically into the startup code for main. and destructors from exit .) FLOAT NOFLOAT These keywords were used in some older linkers to request a particular math subroutine library. ld doesnt use the keywords, assuming instead that any necessary subroutines are in libraries specified using the general mechanisms for linking to archives but to permit the use of scripts that were written for the older linkers, the keywords FLOAT and NOFLOAT are accepted and ignored. FORCECOMMONALLOCATION This command has the same effect as the - d command-line option: to make ld assign space to common symbols even if a relocatable output file is specified ( - r ). INPUT ( file. file. ) INPUT ( file file. ) Use this command to include binary input files in the link, without including them in a particular section definition. Specify the full name for each file. including. a if required. ld searches for each file through the archive-library search path, just as for files you specify on the command line. See the description of - L in xref . If you use - l file . ld will transform the name to lib file. a as with the command line argument - l. GROUP ( file. file. ) GROUP ( file file. ) This command is like INPUT. except that the named files should all be archives, and they are searched repeatedly until no new undefined references are created. See the description of -( in xref . OUTPUT ( filename ) Use this command to name the link output file filename. The effect of OUTPUT( filename ) is identical to the effect of - o filename . which overrides it. You can use this command to supply a default output-file name other than a. out. OUTPUTARCH ( bfdname ) Specify a particular output machine architecture, with one of the names used by the BFD back-end routines (see section BFD ). This command is often unnecessary the architecture is most often set implicitly by either the system BFD configuration or as a side effect of the OUTPUTFORMAT command. OUTPUTFORMAT ( bfdname ) When ld is configured to support multiple object code formats, you can use this command to specify a particular output format. bfdname is one of the names used by the BFD back-end routines (see section BFD ). The effect is identical to the effect of the - oformat command-line option. This selection affects only the output file the related command TARGET affects primarily input files. SEARCHDIR ( path ) Add path to the list of paths where ld looks for archive libraries. SEARCHDIR( path ) has the same effect as - L path on the command line. STARTUP ( filename ) Ensure that filename is the first input file used in the link process. TARGET ( format ) When ld is configured to support multiple object code formats, you can use this command to change the input-file object code format (like the command-line option - b or its synonym - format ). The argument format is one of the strings used by BFD to name binary formats. If TARGET is specified but OUTPUTFORMAT is not, the last TARGET argument is also used as the default format for the ld output file. See section BFD. If you dont use the TARGET command, ld uses the value of the environment variable GNUTARGET. if available, to select the output file format. If that variable is also absent, ld uses the default format configured for your machine in the BFD libraries. Go to the first. previous. next. last section, table of contents. Linux and Unix ld command About ld ld combines a number of object and archive files, relocates their data and ties up symbol references. Usually the last step in compiling a program is to run ld. ld accepts Linker Command Language files written in a superset of ATampT s Link Editor Command Language syntax, to provide explicit and total control over the linking process. For full details on the ld command language, see the ld info page. Here, well cover a broad overview of how to use GNU ld, which is used in most versions of Linux . This version of ld uses the general purpose BFD libraries to operate on object files. This allows ld to read, combine, and write object files in many different formats: for example, COFF or a. out . Different formats may be linked together to produce any available kind of object file. Aside from its flexibility, the GNU linker is more helpful than other linkers in providing diagnostic information. Many linkers abandon execution immediately upon encountering an error whenever possible, ld continues executing, allowing you to identify other errors (or, in some cases, to get an output file in spite of the error). The GNU linker ld is meant to cover a broad range of situations, and to be as compatible as possible with other linkers. As a result, you have many choices to control its behavior. ld syntax Options The linker supports many command-line options, but in actual practice few of them are used in any particular context. For instance, a frequent use of ld is to link standard Unix object files on a standard, supported Unix system. On such a system, to link a file hello. o : This tells ld to produce a file called output as the result of linking the file /lib/crt0.o with hello. o and the library libc. a , which will come from the standard search directories. See the - l option below. Some of the command-line options to ld may be specified at any point in the command line. However, options which refer to files, such as - l or - T . cause the file to be read at the point at which the option appears in the command line, relative to the object files and other file options. Repeating non-file options with a different argument will either have no further effect, or override prior occurrences (those further to the left on the command line) of that option. Options which may be meaningfully specified more than once are noted in the descriptions below. Non-option arguments are object files or archives which are to be linked together. They may follow, precede, or be mixed in with command-line options, except that an object file argument may not be placed between an option and its argument. Usually the linker is invoked with at least one object file, but you can specify other forms of binary input files using - l . - R . and the script command language. If no binary input files at all are specified, the linker does not produce any output, and issues the message No input files . If the linker cannot recognize the format of an object file, it will assume that it is a linker script. A script specified in this way augments the main linker script used for the link (either the default linker script or the one specified by using - T ). This feature permits the linker to link against a file which appears to be an object or an archive. but actually merely defines some symbol values, or uses INPUT or GROUP to load other objects. Specifying a script in this way merely augments the main linker script, with the extra commands placed after the main script use the - T option to replace the default linker script entirely, but note the effect of the INSERT command. For options whose names are a single letter, option arguments must either follow the option letter without intervening whitespace. or be given as separate arguments immediately following the option that requires them. For options whose names are multiple letters, either one dash or two can precede the option name for example, - trace-symbol and --trace-symbol are equivalent. Note that there is one exception to this rule: Multiple letter options that start with a lower case o can only be preceded by two dashes. This is to reduce confusion with the - o option. So for example - omagic sets the output file name to magic whereas --omagic sets the NMAGIC flag on the output. Arguments to multiple-letter options must either be separated from the option name by an equals sign, or be given as separate arguments immediately following the option that requires them. For example, --trace-symbol foo and --trace-symbolfoo are equivalent. Unique abbreviations of the names of multiple-letter options are accepted. Note that if the linker is being invoked indirectly, via a compiler driver (e. g. gcc ) then all the linker command line options should be prefixed by - Wl . (or whatever is appropriate for the particular compiler driver) like this: This is important, because otherwise the compiler driver program may silently drop the linker options, resulting in a bad link. Confusion may also arise when passing options that require values through a driver, as the use of a space between option and argument acts as a separator, and causes the driver to pass only the option to the linker and the argument to the compiler. In this case, it is simplest to use the joined forms of both single - and multiple-letter options, such as: Here is a table of the generic command line switches accepted by the GNU linker: Read command-line options from file . The options read are inserted in place of the original file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed. Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional file options any such options will be processed recursively . This option is supported for HP-UX compatibility. The keyword argument must be one of the strings archive . shared . or default . - aarchive is functionally equivalent to - Bstatic . and the other two keywords are functionally equivalent to - Bdynamic . This option may be used any number of times. Adds AUDITLIB to the DTAUDIT entry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DTSONAME specified in the library. If specified multiple times DTAUDIT will contain a colon separated list of audit interfaces to use. If the linker finds an object with an audit entry while searching for shared libraries, it will add a corresponding DTDEPAUDIT entry in the output file. This option is only meaningful on ELF platforms supporting the rtld-audit interface. In the current release of ld . this option is useful only for the Intel 960 family of architectures. In that ld configuration, the architecture argument identifies the particular architecture in the 960 family, enabling some safeguards and modifying the archive-library search path. Future releases of ld may support similar functionality for other architecture families. ld may be configured to support more than one kind of object file. If your ld is configured this way, you can use the - b option to specify the binary format for input object files that follow this option on the command line. Even when ld is configured to support alternative object formats, you dont usually need to specify this, as ld should be configured to expect as a default input format the most usual format on each machine. input-format is a text string, the name of a particular format supported by the BFD libraries. You can list the available binary formats with objdump - i . You may want to use this option if you are linking files with an unusual binary format. You can also use - b to switch formats explicitly (when linking object files of different formats), by including - b input-format before each group of object files in a particular format. The default format is taken from the environment variable GNUTARGET. You can also define the input format from a script, using the command TARGET For compatibility with linkers produced by MRI, ld accepts script files written in an alternate, restricted command language, described in the MRI Compatible Script Files section of GNU ld documentation. Introduce MRI script files with the option - c use the - T option to run linker scripts written in the general-purpose ld scripting language. If MRI-cmdfile does not exist, ld looks for it in the directories specified by any - L options. These three options are equivalent multiple forms are supported for compatibility with other linkers. They assign space to common symbols even if a relocatable output file is specified (with - r ). The script command FORCECOMMONALLOCATION has the same effect. Adds AUDITLIB to the DTDEPAUDIT entry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DTSONAME specified in the library. If specified multiple times DTDEPAUDIT will contain a colon separated list of audit interfaces to use. This option is only meaningful on ELF platforms supporting the rtld-audit interface. The - P option is provided for Solaris compatibility. Use entry as the explicit symbol for beginning execution of your program, rather than the default entry point. If there is no symbol named entry . the linker will try to parse entry as a number, and use that as the entry address (the number will be interpreted in base 10 you may use a leading 0x for base 16, or a leading 0 for base 8). Specifies a list of archive libraries from which symbols should not be automatically exported. The library names may be delimited by commas or colons. Specifying --exclude-libs ALL excludes symbols in all archive libraries from automatic export. This option is available only for the i386 PE targeted port of the linker and for ELF targeted ports. For i386 PE, symbols explicitly listed in a. def file are still exported, regardless of this option. For ELF targeted ports, symbols affected by this option will be treated as hidden. Specifies a list of object files or archive members, from which symbols should not be automatically exported, but which should be copied wholesale into the import library being generated during the link. The module names may be delimited by commas or colons, and must match exactly the filenames used by ld to open the files for archive members, this is simply the member name, but for object files the name listed must include and match precisely any path used to specify the input file on the linkers command-line. This option is available only for the i386 PE targeted port of the linker. Symbols explicitly listed in a. def file are still exported, regardless of this option. When creating a dynamically linked executable, using the - E option or the --export-dynamic option causes the linker to add all symbols to the dynamic symbol table. The dynamic symbol table is the set of symbols which are visible from dynamic objects at run time. If you do not use either of these options (or use the --no-export-dynamic option to restore the default behavior), the dynamic symbol table will normally contain only those symbols which are referenced by some dynamic object mentioned in the link. If you use dlopen to load a dynamic object which needs to refer back to the symbols defined by the program, rather than some other dynamic object, then you will probably need to use this option when linking the program itself. You can also use the dynamic list to control what symbols should be added to the dynamic symbol table if the output format supports it. See the description of --dynamic-list . Note that this option is specific to ELF targeted ports. PE targets support a similar function to export all symbols from a DLL or EXE see the description of --export-all-symbols below. Link big-endian objects. This affects the default output format. Link little-endian objects. This affects the default output format. When creating an ELF shared object, set the internal DTAUXILIARY field to the specified name. This tells the dynamic linker that the symbol table of the shared object should be used as an auxiliary filter on the symbol table of the shared object name. If you later link a program against this filter object, then, when you run the program, the dynamic linker will see the DTAUXILIARY field. If the dynamic linker resolves any symbols from the filter object, it will first check whether there is a definition in the shared object name. If there is one, it will be used instead of the definition in the filter object. The shared object name need not exist. Thus the shared object name may be used to provide an alternative implementation of certain functions, perhaps for debugging or for machine specific performance. This option may be specified more than once. The DTAUXILIARY entries will be created in the order in which they appear on the command line. When creating an ELF shared object, set the internal DTFILTER field to the specified name. This tells the dynamic linker that the symbol table of the shared object which is being created should be used as a filter on the symbol table of the shared object name. If you later link a program against this filter object, then, when you run the program, the dynamic linker will see the DTFILTER field. The dynamic linker will resolve symbols according to the symbol table of the filter object as usual, but it will actually link to the definitions found in the shared object name. Thus the filter object can be used to select a subset of the symbols provided by the object name. Some older linkers used the - F option throughout a compilation toolchain for specifying object-file format for both input and output object files. The GNU linker uses other mechanisms for this purpose: the - b . --format . --oformat options, the TARGET command in linker scripts, and the GNUTARGET environment variable. The GNU linker will ignore the - F option when not creating an ELF shared object. When creating an ELF executable or shared object, call NAME when the executable or shared object is unloaded, by setting DTFINI to the address of the function. By default, the linker uses fini as the function to call. Ignored. Provided for compatibility with other tools. Set the maximum size of objects to be optimized using the GP register to size. This is only meaningful for object file formats such as MIPS ECOFF which supports putting large and small objects into different sections. This is ignored for other object file formats. When creating an ELF shared object, set the internal DTSONAME field to the specified name. When an executable is linked with a shared object which has a DTSONAME field, then when the executable is run the dynamic linker will attempt to load the shared object specified by the DTSONAME field rather than the using the file name given to the linker. Perform an incremental link (same as option - r ). When creating an ELF executable or shared object, call NAME when the executable or shared object is loaded, by setting DTINIT to the address of the function. By default, the linker uses init as the function to call. Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form : filename . ld will search the library path for a file called filename . otherwise it will search the library path for a file called lib namespec. a . On systems which support shared libraries, ld may also search for files other than lib namespec. a . Specifically, on ELF and SunOS systems, ld will search a directory for a library called lib namespec. so before searching for one called lib namespec. a . By convention, a. so extension indicates a shared library. Note that this behavior does not apply to : filename . which always specifies a file called filename . The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again. See the -( option for a way to force the linker to search archives multiple times. You may list the same archive multiple times on the command line. This type of archive searching is standard for Unix linkers. However, if you are using ld on AIX. note that it is different from the behaviour of the AIX linker. Add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts. You may use this option any number of times. The directories are searched in the order in which they are specified on the command line. Directories specified on the command line are searched before the default directories. All - L options apply to all - l options, regardless of the order in which the options appear. - L options do not affect how ld searches for a linker script unless - T option is specified. If searchdir begins with , then the will be replaced by the sysroot prefix, a path specified when the linker is configured. The default set of paths searched (without being specified with - L ) depends on which emulation mode ld is using, and in some cases also on how it was configured at build time. The paths can also be specified in a link script with the SEARCHDIR command. Directories specified this way are searched at the point in which the linker script appears in the command line. Emulate the emulation linker. You can list the available emulations with the --verbose or - V options. If the - m option is not used, the emulation is taken from the LDEMULATION environment variable, if that is defined. Otherwise, the default emulation depends upon how the linker was configured. Print a link map to the standard output. A link map provides information about the link, including the following: Where object files are mapped into memory. How common symbols are allocated. All archive members included in the link, with a mention of the symbol which caused the archive member to be brought in. The values assigned to symbols. Note: symbols whose values are computed by an expression which involves a reference to a previous value of the same symbol may not have correct result displayed in the link map. This is because the linker discards intermediate results and only retains the final value of an expression. Under such circumstances the linker will display the final value enclosed by square brackets. Thus for example a linker script containing:will produce the following output in the link map if the - M option is used: Turn off page alignment of sections, and disable linking against shared libraries. If the output format supports Unix style magic numbers, mark the output as NMAGIC. Set the text and data sections to be readable and writable. Also, do not page-align the data segment, and disable linking against shared libraries. If the output format supports Unix style magic numbers, mark the output as OMAGIC. Note: Although a writable text section is allowed for PE-COFF targets, it does not conform to the format specification published by Microsoft . This option negates most of the effects of the - N option. It sets the text section to be read-only, and forces the data segment to be page-aligned. Note - this option does not enable linking against shared libraries. Use - Bdynamic for this. Use output as the name for the program produced by ld if this option is not specified, the name a. out is used by default. The script command OUTPUT can also specify the output file name. If level is a numeric value greater than zero ld optimizes the output. This might take significantly longer and therefore probably should only be enabled for the final binary. At the moment this option only affects ELF shared library generation. Future releases of the linker may make more use of this option. Also currently there is no difference in the linkers behaviour for different non-zero values of this option. Again this may change with future releases. Leave relocation sections and contents in fully linked executables. Post link analysis and optimization tools may need this information in order to perform correct modifications of executables. This results in larger executables. This option is currently only supported on ELF platforms. Force the output file to have dynamic sections. This option is specific to VxWorks targets. Generate relocatable output: i. e. generate an output file that can in turn serve as input to ld . This is often called partial linking. As a side effect, in environments that support standard Unix magic numbers, this option also sets the output files magic number to OMAGIC. If this option is not specified, an absolute file is produced. When linking C programs, this option will not resolve references to constructors to do that, use - Ur . When an input file does not have the same format as the output file, partial linking is only supported if that input file does not contain any relocations. Different output formats can have further restrictions for example some a. out - based formats do not support partial linking with input files in other formats at all. This option does the same thing as - i . Read symbol names and their addresses from filename . but do not relocate it or include it in the output. This allows your output file to refer symbolically to absolute locations of memory defined in other programs. You may use this option more than once. For compatibility with other ELF linkers, if the - R option is followed by a directory name, rather than a file name, it is treated as the - rpath option. Omit all symbol information from the output file. Use scriptfile as the linker script. This script replaces ld s default linker script (rather than adding to it), so commandfile must specify everything necessary to describe the output file. If scriptfile does not exist in the current directory, ld looks for it in the directories specified by any preceding - L options. Multiple - T options accumulate. Use scriptfile as the default linker script. This option is similar to the --script option except that processing of the script is delayed until after the rest of the command line has been processed. This allows options placed after the --default-script option on the command line to affect the behaviour of the linker script, which can be important when the linker command line cannot be directly controlled by the user. (e. g. because the command line is being constructed by another tool, such as gcc ). Force symbol to be entered in the output file as an undefined symbol. Doing this may, for example, trigger linking of additional modules from standard libraries. - u may be repeated with different option arguments to enter additional undefined symbols. This option is equivalent to the EXTERN linker script command. For anything other than C programs, this option is equivalent to - r . it generates relocatable output i. e. an output file that can in turn serve as input to ld . When linking C programs, - Ur does resolve references to constructors, unlike - r . It does not work to use - Ur on files that were themselves linked with - Ur once the constructor table has been built, it cannot be added to. Use - Ur only for the last partial link, and - r for the others. Creates a separate output section for every input section matching SECTION, or if the optional wildcard SECTION argument is missing, for every orphan input section. An orphan section is one not specifically mentioned in a linker script. You may use this option multiple times on the command line It prevents the normal merging of input sections with the same name, overriding output section assignments in a linker script. Display the version number for ld . The - V option also lists the supported emulations. Other keywords are ignored for Solaris compatibility. --start-group archives --end-group The archives should be a list of archive files. They may be either explicit file names, or - l options. The specified archives are searched repeatedly until no new undefined references are created. Normally, an archive is searched only once in the order that it is specified on the command line. If a symbol in that archive is needed to resolve an undefined symbol referred to by an object in an archive that appears later on the command line, the linker would not be able to resolve that reference. By grouping the archives, they all be searched repeatedly until all possible references are resolved. Using this option has a significant performance cost. It is best to use it only when there are unavoidable circular references between two or more archives. Tells the linker to accept input files whose architecture cannot be recognised. The assumption is that the user knows what they are doing and deliberately wants to link in these unknown input files. This was the default behaviour of the linker, before release 2.14. The default behaviour from release 2.14 onwards is to reject such input files, and so the --accept-unknown-input-arch option has been added to restore the old behaviour. This option affects ELF DTNEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option. Normally the linker will add a DTNEEDED tag for each dynamic library mentioned on the command line, regardless of whether the library is actually needed or not. --as-needed causes a DTNEEDED tag to only be emitted for a library that satisfies an undefined symbol reference from a regular object file or, if the library is not found in the DTNEEDED lists of other libraries linked up to that point, an undefined symbol reference from another dynamic library. --no-as-needed restores the default behaviour. These two options have been deprecated because of the similarity of their names to the --as-needed and --no-as-needed options. They have been replaced by --copy-dt-needed-entries and --no-copy-dt-needed-entries . This option is ignored for SunOS compatibility. Link against dynamic libraries. Isso só é significativo em plataformas para as quais bibliotecas compartilhadas são suportadas. This option is normally the default on such platforms. The different variants of this option are for compatibility with various systems. You may use this option multiple times on the command line: it affects library searching for - l options which follow it. Set the DF1GROUP flag in the DTFLAGS1 entry in the dynamic section. This causes the runtime linker to handle lookups in this object and its dependencies to be performed only inside the group. --unresolved-symbolsreport-all is implied. This option is only meaningful on ELF platforms which support shared libraries. Do not link against shared libraries. Isso só é significativo em plataformas para as quais bibliotecas compartilhadas são suportadas. The different variants of this option are for compatibility with various systems. You may use this option multiple times on the command line: it affects library searching for - l options which follow it. This option also implies --unresolved-symbolsreport-all . This option can be used with - shared . Doing so means that a shared library is being created but that all of the librarys external references must be resolved by pulling in entries from static libraries. When creating a shared library, bind references to global symbols to the definition within the shared library, if any. Normally, it is possible for a program linked against a shared library to override the definition within the shared library. This option is only meaningful on ELF platforms which support shared libraries. When creating a shared library, bind references to global function symbols to the definition within the shared library, if any. This option is only meaningful on ELF platforms which support shared libraries. Specify the name of a dynamic list file to the linker. This is typically used when creating shared libraries to specify a list of global symbols whose references shouldnt be bound to the definition within the shared library, or creating dynamically linked executables to specify a list of symbols which should be added to the symbol table in the executable. This option is only meaningful on ELF platforms which support shared libraries. The format of the dynamic list is the same as the version node without scope and node name. Include all global data symbols to the dynamic list. Provide the builtin dynamic list for C operator new and delete. It is mainly useful for building shared libstdc. Provide the builtin dynamic list for C runtime type identification. Asks the linker not to check section addresses after they have been assigned to see if there are any overlaps. Normally the linker will perform this check, and if it finds any overlaps it will produce suitable error messages. The linker does know about, and does make allowances for sections in overlays. The default behaviour can be restored by using the command line switch --check-sections . Section overlap is not usually checked for relocatable links. You can force checking in that case by using the --check-sections option. This option affects the treatment of dynamic libraries referred to by DTNEEDED tags inside ELF dynamic libraries mentioned on the command line. Normally the linker wont add a DTNEEDED tag to the output binary for each library mentioned in a DTNEEDED tag in an input dynamic library. With --copy-dt-needed-entries specified on the command line however any dynamic libraries that follow it will have their DTNEEDED entries added. The default behaviour can be restored with --no-copy-dt-needed-entries . This option also has an effect on the resolution of symbols in dynamic libraries. With --copy-dt-needed-entries dynamic libraries mentioned on the command line will be recursively searched, following their DTNEEDED tags to other libraries, in order to resolve symbols required by the output binary. With the default setting however the searching of dynamic libraries that follow it will stop with the dynamic library itself. No DTNEEDED links will be traversed to resolve symbols. Output a cross reference table. If a linker map file is being generated, the cross reference table is printed to the map file. Otherwise, it is printed on the standard output. The format of the table is intentionally simple, so that it may be easily processed by a script if necessary. The symbols are printed out, sorted by name. For each symbol, a list of file names is given. If the symbol is defined, the first file listed is the location of the definition. The remaining files contain references to the symbol. This option inhibits the assignment of addresses to common symbols. The script command INHIBITCOMMONALLOCATION has the same effect. The --no-define-common option allows decoupling the decision to assign addresses to Common symbols from the choice of the output file type otherwise a non-Relocatable output type forces assigning addresses to Common symbols. Using --no-define-common allows Common symbols that are referenced from a shared library to be assigned addresses only in the main program. This eliminates the unused duplicate space in the shared library, and also prevents any possible confusion over resolving to the wrong duplicate when there are many dynamic modules with specialized search paths for runtime symbol resolution. Create a global symbol in the output file, containing the absolute address given by expression . You may use this option as many times as necessary to define multiple symbols in the command line. A limited form of arithmetic is supported for the expression in this context: you may give a hexadecimal constant or the name of an existing symbol, or use and - to add or subtract hexadecimal constants or symbols. If you need more elaborate expressions, consider using the linker command language from a script. Note: there should be no white space between symbol, the equals sign ( ), and expression . These options control whether to demangle symbol names in error messages and other output. When the linker is told to demangle, it tries to present symbol names in a readable fashion: it strips leading underscores if they are used by the object file format, and converts C mangled symbol names into user readable names. Different compilers have different mangling styles. The optional demangling style argument can be used to choose an appropriate demangling style for your compiler. The linker will demangle by default unless the environment variable COLLECTNODEMANGLE is set. These options may be used to override the default. Set the name of the dynamic linker. This is only meaningful when generating dynamically linked ELF executables. The default dynamic linker is normally correct dont use this unless you know what you are doing. Treat all warnings as errors. The default behaviour can be restored with the option --no-fatal-warnings . Make sure that an output file has a. exe suffix. If a successfully built fully linked output file does not have a. exe or. dll suffix, this option forces the linker to copy the output file to one of the same name with a. exe suffix. This option is useful when using unmodified Unix makefiles on a Microsoft Windows host, since some versions of Windows wont run an image unless it ends in a. exe suffix. Enable garbage collection of unused input sections. It is ignored on targets that do not support this option. The default behaviour (of not performing this garbage collection) can be restored by specifying --no-gc-sections on the command line. --gc-sections decides which input sections are used by examining symbols and relocations. The section containing the entry symbol and all sections containing symbols undefined on the command-line will be kept, as will sections containing symbols referenced by dynamic objects. Note that when building shared libraries, the linker must assume that any visible symbol is referenced. Once this initial set of sections has been determined, the linker recursively marks as used any section referenced by their relocations. See --entry and --undefined . This option can be set when doing a partial link (enabled with option - r ). In this case the root of symbols kept must be explicitly specified either by an --entry or --undefined option or by a ENTRY command in the linker script. List all sections removed by garbage collection. The listing is printed on stderr. This option is only effective if garbage collection has been enabled via the --gc-sections ) option. The default behaviour (of not listing the sections that are removed) can be restored by specifying --no-print-gc-sections on the command line. Print the name of the default output format (perhaps influenced by other command-line options). This is the string that would appear in an OUTPUTFORMAT linker script command. Print a summary of the command-line options on the standard output and exit. Report unresolved symbols that are contained in shared libraries, but ignore them if they come from regular object files. Report unresolved symbols that come from regular object files, but ignore them if they come from shared libraries. This can be useful when creating a dynamic binary and it is known that all the shared libraries that it should be referencing are included on the linkers command line. The behaviour for shared libraries on their own can also be controlled by the -- no - allow-shlib-undefined option. Normally the linker will generate an error message for each reported unresolved symbol but the option --warn-unresolved-symbols can change this to a warning. Display the version number for ld and list the linker emulations supported. Display which input files can and cannot be opened. Display the linker script being used by the linker. If the optional NUMBER argument gt 1 . plugin symbol status will also be displayed. Specify the name of a version script to the linker. This is typically used when creating shared libraries to specify additional information about the version hierarchy for the library being created. This option is only fully supported on ELF platforms which support shared libraries. It is partially supported on PE platforms, which can use version scripts to filter symbol visibility in auto-export mode: any symbols marked local in the version script will not be exported. Warn when a common symbol is combined with another common symbol or with a symbol definition. Unix linkers allow this somewhat sloppy practice, but linkers on some other operating systems do not. This option allows you to find potential problems from combining global symbols. Unfortunately, some C libraries use this practice, so you may get some warnings about symbols in the libraries as well as in your programs. There are three kinds of global symbols, illustrated here by C examples: A definition, which goes in the initialized data section of the output file. An undefined reference, which does not allocate space. There must be either a definition or a common symbol for the variable somewhere. A common symbol. If there are only (one or more) common symbols for a variable, it goes in the uninitialized data area of the output file. The linker merges multiple common symbols for the same variable into a single symbol. If they are of different sizes, it picks the largest size. The linker turns a common symbol into a declaration, if there is a definition of the same variable. The --warn-common option can produce five kinds of warnings. Each warning consists of a pair of lines: the first describes the symbol just encountered, and the second describes the previous symbol encountered with the same name. One or both of the two symbols will be a common symbol. 1. Turning a common symbol into a reference, because there is already a definition for the symbol. 2. Turning a common symbol into a reference, because a later definition for the symbol is encountered. This is the same as the previous case, except that the symbols are encountered in a different order. 3. Merging a common symbol with a previous same-sized common symbol. 4. Merging a common symbol with a previous larger common symbol. 5. Merging a common symbol with a previous smaller common symbol. This is the same as the previous case, except that the symbols are encountered in a different order. Warn if any global constructors are used. This is only useful for a few object file formats. For formats like COFF or ELF, the linker can not detect the use of global constructors. Warn if multiple global pointer values are required in the output file. This is only meaningful for certain processors, such as the DEC Alpha. Specifically, some processors put large-valued constants in a special section. A special register (the global pointer) points into the middle of this section, so that constants can be loaded efficiently via a base-register relative addressing mode. Since the offset in base-register relative mode is fixed and relatively small (e. g. 16 bits ), this limits the maximum size of the constant pool. Thus, in large programs, it is often necessary to use multiple global pointer values in order to be able to address all possible constants. This option causes a warning to be issued whenever this case occurs. Only warn once for each undefined symbol, rather than once per module which refers to it. Warn if the address of an output section is changed because of alignment. Typically, the alignment will be set by an input section. The address will only be changed if it not explicitly specified that is, if the SECTIONS command does not specify a start address for the section. Warn if the linker adds a DTTEXTREL to a shared object.
No comments:
Post a Comment